Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

csv.write skipping lines when writing to csv

Tags:

python

csv

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

like image 265
user1266138 Avatar asked Jul 25 '12 15:07

user1266138


People also ask

How do I stop repeating header when writing CSV?

Create an if condition to check for the need for writing headers. If headers exist no need to write headers. Empty/new CSV = write headers and you can leave out the writing header from that point on. I've gone ahead and added a section that will answer your loop question.

How do you read and write in CSV at the same time?

You can do open("data. csv", "rw") , this allows you to read and write at the same time.

How do I skip the first line in a CSV file?

In Python, while reading a CSV using the CSV module you can skip the first line using next() method.


1 Answers

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() 
like image 150
Lanaru Avatar answered Sep 16 '22 12:09

Lanaru