本文介绍了Python CSV文件写入列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何在python中写入csv文件,以便得到一个列表(这是列表的列表)
How I can write into a csv file in python so that,a list(which is a list of lists)
[['CL07001006', 'IM20010809'], ['IM75630511', 'IM75550511', 'IM75610511', 'IM75640511', 'IM75500511'],['CL0700100r','CL0700100U','PL07001006']]
采用以下格式:
CL07001006 IM75630511 CL0700100r
IM20010809 IM75550511 CL0700100U
IM75610511 PL07001006
IM75640511
IM75500511
我尝试了以下操作:
def demo():
lol = [['CL07001006', 'IM20010809'], ['IM75630511', 'IM75550511', 'IM75610511', 'IM75640511', 'IM75500511']]
file = open("dummy.csv", 'wb')
fileWritter = csv.writer(file, delimiter='\n',quotechar='|', quoting=csv.QUOTE_MINIMAL)
for l in lol:
fileWritter.writerow(l)
if __name__ == '__main__':
demo()
结果如下:
CL07001006
IM20010809
IM75630511
IM75610511
IM75640511
IM75500511
谢谢.
推荐答案
>>> import itertools
>>> import csv
>>> x = [['CL07001006', 'IM20010809'], ['IM75630511', 'IM75550511', 'IM75610511', 'IM75640511', 'IM75500511'],['CL0700100r','CL0700100U','PL07001006']]
>>> outs = csv.writer(open("out.csv", "wb"))
>>> for row in itertools.izip_longest(*x):
... outs.writerow(row)
...
>>> ^D
$ cat "out.csv"
CL07001006,IM75630511,CL0700100r
IM20010809,IM75550511,CL0700100U
,IM75610511,PL07001006
,IM75640511,
,IM75500511,
这篇关于Python CSV文件写入列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!