如何使用io.StringIO()与csv模块? [英] How can I use io.StringIO() with the csv module?
问题描述
我试图将一个Python 3程序退回到2.7,我遇到了一个奇怪的问题:
I tried to backport a Python 3 program to 2.7, and I'm stuck with a strange problem:
>>> import io
>>> import csv
>>> output = io.StringIO()
>>> output.write("Hello!") # Fail: io.StringIO expects Unicode
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unicode argument expected, got 'str'
>>> output.write(u"Hello!") # This works as expected.
6L
>>> writer = csv.writer(output) # Now let's try this with the csv module:
>>> csvdata = [u"Hello", u"Goodbye"] # Look ma, all Unicode! (?)
>>> writer.writerow(csvdata) # Sadly, no.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unicode argument expected, got 'str'
根据文档, io.StringIO()
返回Unicode文本的内存中流。它工作正常,当我尝试和喂它一个Unicode字符串手动。为什么它与 csv
模块结合失败,即使所有被编写的字符串都是Unicode字符串? str
在哪里导致异常?
According to the docs, io.StringIO()
returns an in-memory stream for Unicode text. It works correctly when I try and feed it a Unicode string manually. Why does it fail in conjunction with the csv
module, even if all the strings being written are Unicode strings? Where does the str
come from that causes the Exception?
(我知道我可以使用 StringIO.StringIO()
,但我想知道在这种情况下 io.StringIO()
(I do know that I can use StringIO.StringIO()
instead, but I'm wondering what's wrong with io.StringIO()
in this scenario)
推荐答案
Python 2.7 csv
支持Unicode输入:请参阅文档开头的注释。
The Python 2.7 csv
module doesn't support Unicode input: see the note at the beginning of the documentation.
您似乎必须将Unicode字符串编码为字节字符串,并使用 io.BytesIO
,而不是 io.StringIO
。
It seems that you'll have to encode the Unicode strings to byte strings, and use io.BytesIO
, instead of io.StringIO
.
examples 部分包含 UnicodeReader
和 UnicodeWriter
封装的示例类(感谢@AlexeyKachayev的指针)。
The examples section of the documentation includes examples for a UnicodeReader
and UnicodeWriter
wrapper classes (thanks @AlexeyKachayev for the pointer).
这篇关于如何使用io.StringIO()与csv模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!