這裏是一個全功能的例子。
此腳本不使用任何庫,並在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()
,你必須每行寫一行。 –