From: tkpmep on
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?

Thank you in advance

Thomas Philips
From: Peter Otten on
tkpmep(a)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
From: tkpmep on
Worked like a charm! Thank you very much.

From: Terry Reedy on
On 4/27/2010 9:05 AM, tkpmep(a)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

In 3.x, t vs b modes actually mean to read/write text (str (unicode)) vs
binary (bytes, for instance) objects.