Python3写入gzip文件-memoryview:需要一个类似字节的对象,而不是'str' [英] Python3 write gzip file - memoryview: a bytes-like object is required, not 'str'

查看:196
本文介绍了Python3写入gzip文件-memoryview:需要一个类似字节的对象,而不是'str'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个文件.根据文件名,可以使用gzip模块进行压缩,也可以不进行压缩.这是我的代码:

I want to write a file. Based on the name of the file this may or may not be compressed with the gzip module. Here is my code:

import gzip
filename = 'output.gz'
opener = gzip.open if filename.endswith('.gz') else open
with opener(filename, 'wb') as fd:
    print('blah blah blah'.encode(), file=fd)

我正在以二进制模式打开可写文件,并对要写入的字符串进行编码.但是我收到以下错误:

I'm opening the writable file in binary mode and encoding my string to be written. However I get the following error:

File "/usr/lib/python3.5/gzip.py", line 258, in write
  data = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'str'

为什么我的对象不是字节?如果使用'w'打开文件并跳过编码步骤,则会遇到相同的错误.如果我从文件名中删除'.gz',也会遇到相同的错误.

Why is my object not a bytes? I get the same error if I open the file with 'w' and skip the encoding step. I also get the same error if I remove the '.gz' from the filename.

我在Ubuntu 16.04上使用Python3.5

I'm using Python3.5 on Ubuntu 16.04

推荐答案

print是一个相对复杂的函数.它将str写入文件,但不将您传递的str写入文件,并写入作为呈现参数结果的str.

print is a relatively complex function. It writes str to a file but not the str that you pass, it writes the str that is the result of rendering the parameters.

如果已经有字节,则可以直接使用fd.write(bytes),并在需要时注意添加换行符.

If you have bytes already, you can use fd.write(bytes) directly and take care of adding a newline if you need it.

如果没有字节,请确保打开fd以接收文本.

If you don't have bytes, make sure fd is opened to receive text.

这篇关于Python3写入gzip文件-memoryview:需要一个类似字节的对象,而不是'str'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆