【问题标题】:manipulation of csv format in python files在 python 文件中操作 csv 格式
【发布时间】:2018-04-27 12:12:53
【问题描述】:

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

这是我的代码:

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

【问题讨论】:

  • writer.writerow(graph_zip_file) 替换为writer.writerows(graph_zip_file)

标签: python-2.7 list csv matrix


【解决方案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)

它们都应该返回相同的东西,这就是您指定的所需输出。

我希望这证明有用。

【讨论】:

  • 我将 writrow 更改为 writeros 并且效果很好。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-09
  • 2015-12-07
  • 2023-04-09
相关资源
最近更新 更多