Python 2.7 python文件中csv格式的操作

Python 2.7 python文件中csv格式的操作,python-2.7,list,csv,matrix,Python 2.7,List,Csv,Matrix,我使用zip语法组合了两个列表。当我以csv格式保存它时,整个数据都保存在excell的一个单元格中。我想要的是:压缩文件的每个元素都应该保留在每一行上 这是我的代码: list_of_first_column=["banana","cat","brown"] list_of_second_column=["fruit","animal","color"] graph_zip_file=zip(list_of_first_column,list_of_second_column) with o

我使用zip语法组合了两个列表。当我以csv格式保存它时,整个数据都保存在excell的一个单元格中。我想要的是:压缩文件的每个元素都应该保留在每一行上

这是我的代码:

list_of_first_column=["banana","cat","brown"]
list_of_second_column=["fruit","animal","color"]

graph_zip_file=zip(list_of_first_column,list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(graph_zip_file)
我想要csv格式的内容:

banana,fruit
cat,animal
brown,color

假设您使用的是
csv
模块,那么有两种方法可以做到这一点。您可以使用
writer.writerows

list_of_first_column = ["banana", "cat", "brown"]
list_of_second_column = ["fruit", "animal", "color"]

graph_zip_file = zip(list_of_first_column, list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerows(graph_zip_file)
或者,您可以使用
writer.writerow
for loop

list_of_first_column = ["banana", "cat", "brown"]
list_of_second_column = ["fruit", "animal", "color"]

graph_zip_file = zip(list_of_first_column, list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    for row in graph_zip_file
        writer.writerow(row)
它们都应该返回相同的内容,这就是您所指示的所需输出


我希望这证明是有用的。

writer.writerow(graph\u zip\u文件)
替换为
writer.writerow(graph\u zip\u文件)
。我将writerow改为writeros,效果很好。非常感谢