Tara
Tara

Reputation: 1

Dictionary to CSV - output file has an empty line between every entry

I'm trying to write this dictionary to csv, however, when I open the csv, I am getting an empty line between every line (look like below). I should mention, I am self taught but would really love some help!

import csv
final = [{'length': 20, 'end': datetime.date(2003, 8, 3), 'start': datetime.date(2003, 7, 15)},
         {'length': 22, 'end': datetime.date(2003, 8, 31), 'start': datetime.date(2003, 8, 10)},
         {'length': 15, 'end': datetime.date(2004, 5, 20), 'start': datetime.date(2004, 5, 6)}]

with open('T34.csv', 'w+') as output:
    writer = csv.DictWriter(output, fieldnames = ['start','end','length'])
    writer.writeheader()
    writer.writerows(final)

Output looks like:

picture of excel screen shot

Upvotes: 0

Views: 930

Answers (1)

Allen Qin
Allen Qin

Reputation: 19957

To make your original code working, you just need to add one parameter because by default it use Windows-style line terminators (\r\n).

writer = csv.DictWriter(output, fieldnames = ['start','end','length'],lineterminator='\n')

If you don't mind using a different method, you can use pandas:

import pandas as pd
final = [{'length': 20, 'end': datetime.date(2003, 8, 3), 'start': datetime.date(2003, 7, 15)},
         {'length': 22, 'end': datetime.date(2003, 8, 31), 'start': datetime.date(2003, 8, 10)},
         {'length': 15, 'end': datetime.date(2004, 5, 20), 'start': datetime.date(2004, 5, 6)}]
#convert your dict to a dataframe
df = pd.DataFrame(columns=['start','end','length'],data = final)
#write to csv.
df.to_csv('T34.csv',index=None)

Upvotes: 1

Related Questions