这里是一个全功能的例子。
此脚本不使用任何库,并在Python 2.7
中运行。只需确保每个值都用逗号分隔,就可以创建CSV(逗号分隔值)文件。另外,我不使用itertools
,而是使用map
函数。
# Python 2.7
# Here is an example of three lists of different lengths
aList = [9,8,2,5,14,6]
bList = [8,7,5,4]
cList = [9,15,25,60,47,88,3]
# Creates your empty CSV file
output_file = open(r'C:\Temp\output.csv', 'w')
# Adds headers in the first row
output_file.write('aList,bList,cList\n')
# Adds all the elements from the lists, row-by-row
for a, b, c in map(None, aList, bList, cList):
output_file.write('%s,%s,%s\n' % (a, b, c))
# Closes your file
output_file.close()
在Python 3
中,map
功能不再支持None
是一个映射函数。在这种情况下,从itertools
库zip_longest
功能可能是你不能写每个元素的CSV元素最干净的方法(注意,在Python 2.7
,从itertools
这个函数被调用izip_longest
)
# Python 3.x
import itertools
# Here is an example of three lists of different lengths
aList = [9,8,2,5,14,6]
bList = [8,7,5,4]
cList = [9,15,25,60,47,88,3]
# Creates your empty CSV file
output_file = open(r'C:\Temp\output.csv', 'w')
# Adds headers in the first row
output_file.write('aList,bList,cList\n')
# Adds all the elements from the lists, row-by-row
for a, b, c in itertools.zip_longest(aList, bList, cList):
output_file.write('%s,%s,%s\n' % (a, b, c))
# Closes your file
output_file.close()
,你必须每行写一行。 –