将python列表中的数据逐行写入csv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14134237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:34:07  来源:igfitidea点击:

writing data from a python list to csv row-wise

pythoncsv

提问by

Using python, i am writing data from a list to a .csv file, row-wise.

使用 python,我将数据从列表写入 .csv 文件,逐行。

Code:

代码:

writer=csv.writer(open(filepath,'wb'))
header=['type','id','numberOfUpdates','isPingEnabled','lastUpdated']
length_list=len(header)
i=0

while i!=length_list :
    data=header[i]
    print data
    i=i+1
    writer.writerow(data)

Result: Data is being written to csv file but each letter is printed in each column.

结果:数据正在写入 csv 文件,但每个字母都打印在每列中。

For example: type is written as 't' in one column, 'y' in next column and so on. I need the whole word in one column. Can some one point out what change can i make?

例如:类型在一行中写为“t”,在下一列中写为“y”,依此类推。我需要一栏中的整个词。有人可以指出我可以做出什么改变吗?

Thanks

谢谢

采纳答案by Tim

Change writer.writerow(data)to writer.writerow([data]).

更改writer.writerow(data)writer.writerow([data])

.writerowtakes an iterable and uses each element of that iterable for each column. If you use a list with only one element it will be placed in a single column.

.writerow获取一个可迭代对象并为每一列使用该可迭代对象的每个元素。如果您使用只有一个元素的列表,它将被放置在单个列中。

You should also restructure your loop:

你还应该重构你的循环:

for word in header:
    writer.writerow([word])

回答by Minhaj Javed

This work for me:

这对我有用:

for item in RESULTS:
     wr.writerow([item,])