csv and mixed lists of unicode and numbers

Peter Otten __peter__ at web.de
Tue Nov 24 17:02:27 EST 2009


Sibylle Koczian wrote:

> This problem really goes away with Python 3 (tried it on another
> machine), but something else changes too: in Python 2.6 the
> documentation for the csv module explicitly says "If csvfile is a file
> object, it must be opened with the ‘b’ flag on platforms where that
> makes a difference." The documentation for Python 3.1 doesn't have this
> sentence, and if I do that in Python 3.1 I get for all sorts of data,
> even for a list with only one integer literal:
> 
> TypeError: must be bytes or buffer, not str

Read the documentation for open() at

http://docs.python.org/3.1/library/functions.html#open

There are significant changes with respect to 2.x; you won't even get a file 
object anymore:

>>> open("tmp.txt", "w")
<_io.TextIOWrapper name='tmp.txt' encoding='UTF-8'>
>>> _.write("yadda")
5
>>> open("tmp.dat", "wb")
<_io.BufferedWriter name='tmp.dat'>
>>> _.write("yadda")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: write() argument 1 must be bytes or buffer, not str
>>> open("tmp.dat", "wb").write(b"yadda")
5

If you specify the "b" flag in 3.x the write() method expects bytes, not 
str. The translation of newlines is now controlled by the "newline" 
argument.

Peter




More information about the Python-list mailing list