問(wèn)題描述
python 的 csv writer 不再支持二進(jìn)制模式了嗎?
Does python's csv writer not support binary mode anymore?
直到現(xiàn)在我才不得不在 'b' 模式下寫(xiě)入,但我遇到了非常煩人的錯(cuò)誤,如下所示:
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)
如果有人能解釋錯(cuò)誤,那就太好了.我傳入了一個(gè)迭代,其中每個(gè)元素都是一個(gè)字節(jié)序列,但我仍然收到一個(gè)錯(cuò)誤,即輸入不是字節(jié)"而是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.
我知道如果我關(guān)閉二進(jìn)制模式,上面的代碼片段可以寫(xiě)入普通文件.如果有人有建設(shè)性的解決方案或建議,我將非常感激.
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
模塊總是嘗試寫(xiě)入字符串,而不是字節(jié):
The csv
module in Python 3 always attempts to write strings, not bytes:
為了盡可能輕松地與實(shí)現(xiàn) DB API 的模塊進(jìn)行交互,值 None 被寫(xiě)為空字符串.[...] 所有其他非字符串?dāng)?shù)據(jù)在寫(xiě)入之前都使用 str() 進(jìn)行字符串化.
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.
這意味著你必須向它傳遞一個(gè)接受字符串的文件對(duì)象,這通常意味著以文本模式打開(kāi)它.
That means you have to pass it a file object that accepts strings, which usually means opening it in text mode.
如果您遇到需要字節(jié)的文件對(duì)象,請(qǐng)將其包裝在 io.TextIOWrapper
處理 str->bytes 編碼:
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)
這篇關(guān)于如何以二進(jìn)制模式編寫(xiě)csv文件?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!