26
votes

I am trying to write to a csv file via the following

file = open('P:\test.csv', 'a') 

fieldnames = ('ItemID', 'Factor', 'FixedAmount')
wr = csv.DictWriter(file, fieldnames=fieldnames)
headers = dict((n, n) for n in fieldnames)

wr.writerow(headers)
wr.writerow({'ItemID':1, 'Factor': 2, 'FixedAmount':3})

However, when I look at the csv-file the first row is empty, the second row is my header, the third row is empty again and the fourth ow shows the entries 1,2 and 3. why does it >skip one row before it makes an entry?

EDIT: using python 3.2

5
I can't reproduce. Output is OK at my box. Maybe your real data contains newlines somewhere? - Kos
Btw use wr.writeheader() instead of wr.writerow(headers).. - Tisho
thanks, but with exactly that input, it skips the lines - user1266138

5 Answers

47
votes

Solution is to specify the "lineterminator" parameter in the constructor:

file = open('P:\test.csv', 'w')

fields = ('ItemID', 'Factor', 'FixedAmount')
wr = csv.DictWriter(file, fieldnames=fields, lineterminator = '\n')

wr.writeheader()
wr.writerow({'ItemID':1, 'Factor': 2, 'FixedAmount':3})
file.close()
10
votes

Twenty quatloos says you're running under windows (well, a hundred, given that your file is called P:\test.csv). You're probably getting extra \rs.

[edit]

Okay, since using binary mode causes other problems, how about this:

file = open('P:\test.csv', 'w', newline='')
0
votes

Could it be that you are opening the output file in append mode?

file = open('P:\test.csv', 'a') 
#                           ^

Instead of write mode? If you run the program several times, the output from every run will be in that file...

0
votes

You need to pass an additional parameter to the 'open()' function:

file = open('P:\test.csv', 'a', newline='')

This will keep it from skipping lines.

-1
votes

I had this problem and it was because I was using \n\r. I changed to \n and it is working now.