将已排序元组的列表另存为CSV

Edm*_*mon 23 python csv tuples

我有一个按值排序的元组列表.它们的形式(name,count)是count是每个唯一名称的出现次数.

我想取这个列表并将其转换为CSV,其中每个名称都是列标题,每个值都是单行的列值.

有什么建议怎么办?谢谢.

daw*_*awg 54

你可以这样做:

import csv

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
Run Code Online (Sandbox Code Playgroud)

输出文件将具有:

name,num
"smith, bob",2
carol,3
ted,4
alice,5
Run Code Online (Sandbox Code Playgroud)

  • 在Python 3中,使用模式"w"而不是"wb",以避免出现TypeError.您可以传递`newline =''`,它将处理多余的空白行. (14认同)
  • 我收到此错误,需要类似字节的对象而不是 str。 (2认同)

0x9*_*x90 5

Python,转置列表并写入 CSV 文件

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])
Run Code Online (Sandbox Code Playgroud)

输出

1,4,7
2,5,8
3,6,9
Run Code Online (Sandbox Code Playgroud)

请注意,在 python 3 中尝试可能会出现TypeError: a bytes-like object is required, not 'str' in python and CSV 中提到的错误。

考虑用于with open('ur file.csv','w') as out:python 3。