Wie kann ich io.StringIO () mit dem CSV-Modul verwenden?
Ich habe versucht, ein Python 3-Programm auf 2.7 zurück zu portieren und habe ein seltsames 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'
Nach den Unterlagen,io.StringIO()
Gibt einen In-Memory-Stream für Unicode-Text zurück. Es funktioniert korrekt, wenn ich versuche, eine Unicode-Zeichenfolge manuell einzugeben. Warum scheitert es in Verbindung mit demcsv
Modul, auch wenn alle geschriebenen Zeichenfolgen Unicode-Zeichenfolgen sind? Wo kommt diestr
kommt da die ausnahme raus?
(Ich weiß, dass ich verwenden kannStringIO.StringIO()
Stattdessen frage ich mich, was los istio.StringIO()
In diesem Szenario)