pythoncsv文件的操作,python文件中csv格式的操作

本文介绍了如何使用Python的csv模块将两个列表通过zip函数合并后,正确地写入CSV文件中。目前的问题是所有数据都保存在了Excel的一个单元格里,而目标是每个元素占一行。解决方案包括使用`writer.writerows()`或者通过for循环配合`writer.writerow()`,这两种方法都能实现预期效果,将zip文件的每一项分别写入CSV文件的不同行。
摘要由CSDN通过智能技术生成

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.

This is my code:

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)

what I want in csv format:

banana,fruit

cat,animal

brown,color

解决方案

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)

Or, you can use writer.writerow and a 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)

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

I hope this proves useful.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值