Python:csvwriter 的问题
我正在尝试将数据(主要是日期、布尔值和浮点数据类型)写入 CSV 文件格式。这是我的代码片段:
# Write data to file
with open(OUTPUT_DIR + output_filename,'w') as outputfile:
wrtr = csv.writer(outputfile, delimiter=',', quotechar='"')
for x, y in datarows.items():
a,b,c,d,e,f,g = (somedate.strft('%Y-%m-%d'),0,6058.7,False,1913736200,0,False)
rowstr = "{0},{1},{2},{3},{4},{5},{6}".format(a,b,c,d,e,f,g)
wrtr.writerow(rowstr)
outputfile.close()
文件内容如下所示:
2,0,0,7,-,10,-,03,",",0,",",6,0,5,8,.,7,",",F,a,l ,s,e,",",1,9,1,3,7,3,6,2,0,0,",",0,",",F,a,l,s,e
我目前正在使用原始文件对象写入文件 - 但我更喜欢使用 csvwrite - 因为这就是它的用途
I am attempting to write data (mostly dates, booleans and float data types) into a CSV file format. Here is a snippet of my code:
# Write data to file
with open(OUTPUT_DIR + output_filename,'w') as outputfile:
wrtr = csv.writer(outputfile, delimiter=',', quotechar='"')
for x, y in datarows.items():
a,b,c,d,e,f,g = (somedate.strft('%Y-%m-%d'),0,6058.7,False,1913736200,0,False)
rowstr = "{0},{1},{2},{3},{4},{5},{6}".format(a,b,c,d,e,f,g)
wrtr.writerow(rowstr)
outputfile.close()
File contents look like this:
2,0,0,7,-,10,-,03,",",0,",",6,0,5,8,.,7,",",F,a,l,s,e,",",1,9,1,3,7,3,6,2,0,0,",",0,",",F,a,l,s,e
I am currently using the raw file object to write to file - but I would prefer to use the csvwrite - since that is what its supposed to be used for
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用 wrtr.writerow([a,b,c,d,e,f,g]) 来代替。
writerow() 参数必须是值列表,而不是文本行。
csv.writer
的想法是,它将根据 CSV 规则格式化行值。您得到的结果是由于
writerow()
将您的rowstr
字符串解释为字符列表。Try
wrtr.writerow([a,b,c,d,e,f,g])
instead.writerow()
parameter must be a list of values, not a text line. The idea ofcsv.writer
is that it will format row values according to CSV rules.The result you have is due to the fact that
writerow()
interpreted yourrowstr
string as a list of characters.看看这个例子也许它可以帮助你:
file.csv
希望这可以帮助你
look at this example maybe it can help you:
file.csv
hope this can help you