如何以二进制模式编写一个csv文件? [英] How to write a csv file in binary mode?
问题描述
python的csv writer是否不再支持二进制模式?
Does python's csv writer not support binary mode anymore?
直到现在我还没有必须以'b'模式编写,并且出现了类似这样的非常烦人的错误:
I haven't had to write in 'b' mode until now and i'm getting very annoying errors like so:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-030fb0c9dc9a> in <module>()
4 with open('test.csv', 'wb') as f:
5 w = csv.writer(f)
----> 6 w.writerows(rows)
TypeError: a bytes-like object is required, not 'str'
代码:
import csv
rows = [b'1,2,3', b'4,5,6', b'7,8,9']
with open('test.csv', 'wb') as f:
w = csv.writer(f)
w.writerows(rows)
如果有人可以解释该错误,那就太好了.我传递的是一个可迭代的地方,其中每个元素都是一个字节序列,但是我仍然收到关于输入不是"bytes"而是"str"的错误.这种行为似乎是意外的.
If anyone could explain the error that would be great. I'm passing in an iterable where every element is a byte sequence but I still get an error about the input not being 'bytes' but instead being 'str.' This behavior seems unexpected.
我知道,如果我关闭二进制模式,上述代码段可以写入普通文件.如果有人有建设性的解决方案或建议,我将不胜感激.
I know the above code snippet can write to a normal file if I turn off the binary mode. If anyone has a solution or suggestion that is constructive I would very much appreciate it.
推荐答案
Python 3中的csv
模块始终尝试写入字符串,而不是字节:
The csv
module in Python 3 always attempts to write strings, not bytes:
为了尽可能容易地与实现DB API的模块接口,将值None写入为空字符串. [...]所有其他非字符串数据在写入之前都用str()进行了字符串处理.
To make it as easy as possible to interface with modules which implement the DB API, the value None is written as the empty string. [...] All other non-string data are stringified with str() before being written.
这意味着您必须向其传递一个接受字符串的文件对象,这通常意味着以文本模式打开它.
That means you have to pass it a file object that accepts strings, which usually means opening it in text mode.
If you are stuck with a file object that wants bytes, wrap it in an io.TextIOWrapper
to handle str->bytes encoding:
# assuming you want utf-8
with io.TextIOWrapper(binary_file, encoding='utf-8', newline='') as text_file:
w = csv.writer(text_file)
这篇关于如何以二进制模式编写一个csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!