python以字节的方式写文件_Python3写入gzip文件-memoryview:需要一个类似字节的对象,而不是'str'...

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'

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.

I'm using Python3.5 on Ubuntu 16.04

解决方案

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.

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值