我想写一个文件。根据文件的名称,可能会或可能不会使用gzip
模块进行压缩。这里是我的代码:Python3写gzip文件 - memoryview:需要一个类似字节的对象,而不是'str'
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)
我打开可写文件的二进制模式和编码我的字符串被写入。但是,我收到以下错误:
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'
,我也会得到同样的错误。
我使用Python3.5在Ubuntu 16.04
它与print(str('blah blah blah'.encode()),file = fd)'一样。 python试图写入bytes对象的字符串表示。 – tdelaney