python文件中csv格式的操作 [英] manipulation of csv format in python files

查看:112
本文介绍了python文件中csv格式的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have combined two lists using zip syntax. When I saved it in csv format, whole data are stayed in one cell of excell. what's that i want is: each element of zipped file should be stay on each row.

这是我的代码:

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:

You've got two ways of doing this, assuming that you're using the csv module. You can either use 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)

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

They both should return the same thing, which is what you've indicated as your desired output.

我希望这证明是有用的.

I hope this proves useful.

这篇关于python文件中csv格式的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆