csv.write skipping lines when writing to csv

Viewed 53744

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 Answers

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.

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

Related