字典到CSV - 输出文件在每个条目之间都有一个空行

时间:2017-04-27 22:56:38

标签: python csv dictionary

我正在尝试将此字典写入csv,但是,当我打开csv时,我在每一行之间得到一个空行(如下图所示)。我应该提一下,我是自学成才,但真的很喜欢一些帮助!

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)

输出如下:

picture of excel screen shot

1 个答案:

答案 0 :(得分:0)

要使原始代码正常工作,您只需添加一个参数,因为默认情况下它使用Windows样式的行终止符(\ r \ n)。

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

如果您不介意使用其他方法,可以使用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)