我有一个按值排序的元组列表。它们的形式(name,count)
是 count 是每个唯一名称的出现次数。
我想将此列表转换为 CSV,其中每个名称都是列标题,每个值都是单行的列值。
有什么建议怎么做吗?谢谢。
你可以这样做:
import csv
# note: If you use 'b' for the mode, you will get a TypeError
# under Python3. You can just use 'w' for Python 3
data=[('smith, bob',2),('carol',3),('ted',4),('alice',5)]
with open('ur file.csv','wb') as out:
csv_out=csv.writer(out)
csv_out.writerow(['name','num'])
for row in data:
csv_out.writerow(row)
# You can also do csv_out.writerows(data) instead of the for loop
输出文件将具有:
name,num
"smith, bob",2
carol,3
ted,4
alice,5
import csv
lol = [(1,2,3),(4,5,6),(7,8,9)]
item_length = len(lol[0])
with open('test.csv', 'wb') as test_file:
file_writer = csv.writer(test_file)
for i in range(item_length):
file_writer.writerow([x[i] for x in lol])
输出
1,4,7
2,5,8
3,6,9
请注意,在 python 3 中尝试它可能会出现TypeError: a bytes-like object is required, not 'str' in python 和 CSV中提到的错误。
考虑with open('ur file.csv','w') as out:
用于 python 3。