csv and mixed lists of unicode and numbers
Sibylle Koczian
nulla.epistola at web.de
Wed Nov 25 15:31:14 EST 2009
Terry Reedy schrieb:
> In Python 3, a file opened in 'b' mode is for reading and writing bytes
> with no encoding/decoding. I believe cvs works with files in text mode
> as it returns and expects strings/text for reading and writing. Perhaps
> the cvs doc should say must not be opened in 'b' mode. Not sure.
>
I think that might really be better, because for version 2.6 they
explicitly stated 'b' mode was necessary. The results I couldn't
understand, even after reading the documentation for open():
>>> import csv
>>> acsv = open(r"d:\home\sibylle\temp\tmp.csv", "wb")
>>> row = [b"abc", b"def", b"ghi"]
>>> wtr = csv.writer(acsv)
>>> wtr.writerow(row)
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
wtr.writerow(row)
TypeError: must be bytes or buffer, not str
Same error message with row = [5].
But I think I understand it now: the cvs.writer takes mixed lists of
text and numbers - that's exactly why I like to use it - so it has to
convert them before writing. And it converts into text - even bytes for
a file opened in 'b' mode. Right?
Thank you, everybody, for explaining.
Sibylle
More information about the Python-list
mailing list