Problems with extra blank line when using csv.writer in Python 3.1

Peter Otten __peter__ at web.de
Tue Apr 27 15:54:44 CEST 2010


tkpmep at hotmail.com wrote:

> I’m experiencing a problem with the csv module in Python 3.1.2, and
> would greatly appreciate any help anyone can offer me. When writing
> csv files in Python 2.6, I open the output file as 'wb' to prevent a
> blank line being inserted after every line. Works like a charm. But I
> get an error if I do the same in 3.1; i.e if type the following
> sequence of commands:
>>>> import csv
>>>> outfile = open('c:/temp/test.csv', 'wb')
>>>> writer = csv.writer(outfile)
>>>> line = [1, 2, 3, 4]
>>>> writer.writerow(line)
> Traceback (most recent call last):
>   File "<pyshell#26>", line 1, in <module>
>     writer.writerow(line)
> TypeError: must be bytes or buffer, not str
> 
> 
> Switching to
>>>> outfile = open('c:/temp/test.csv', 'w')
> 
> makes it work, but I now have a blank line after each line when I open
> the file using Excel. Any thoughts or guidance on what I ought to be
> doing in 3.1 to fix the extra blank line problem?

Untested, because I don't have Windows available, but try

outfile = open(filename, "w",  newline="")

Peter



More information about the Python-list mailing list