在python文件中处理csv格式

时间:2017-11-14 13:53:58

标签: 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 open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(graph_zip_file)

我想要的csv格式:

banana,fruit
cat,animal
brown,color

1 个答案:

答案 0 :(得分:1)

假设您正在使用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.writerowfor-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)

他们俩都应该返回相同的东西,这就是你所说的你想要的输出。

我希望这证明有用。