csv.write写入csv时跳过行 [英] csv.write skipping lines when writing to csv

查看:213
本文介绍了csv.write写入csv时跳过行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图通过以下

写入csv文件:

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

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

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

但是,当我看csv文件时,第一行是空的,第二行是我的头,第三行是空的,第四个ow显示条目1,2和3.为什么它在跳过一行之前,它做一个条目?



编辑:使用python 3.2

解决方案

解决方案是在构造函数中指定lineterminator p>

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

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

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

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

解决方案

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()

这篇关于csv.write写入csv时跳过行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆