python之读取和写入csv文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之读取和写入csv文件相关的知识,希望对你有一定的参考价值。

写入csv文件源码:


 1 #输出数据写入CSV文件
 2 import csv
 3 data = [
 4     ("Mike", "male", 24),
 5     ("Lee", "male", 26),
 6     ("Joy", "female", 22)
 7 ]
 8 
 9 #Python3.4以后的新方式,解决空行问题
10 with open(d://write.csv, w, newline=‘‘) as csv_file:
11     csv_writer = csv.writer(csv_file)
12     for list in data:
13         print(list)
14         csv_writer.writerow(list)

读取csv文件源码:


 1 #读取csv文件内容
 2 import csv
 3 list  = []
 4 reader = csv.reader(open("d://demo.csv"))
 5 #csv中有三列数据,遍历读取时使用三个变量分别对应
 6 for title, year, director in reader:
 7   list.append(year)
 8   print(title, "; ",  year , "; ",  director)
 9 
10 print(list)

 

读取运行结果:

技术分享

以上是关于python之读取和写入csv文件的主要内容,如果未能解决你的问题,请参考以下文章

csv文件怎么打开 使用Python读取和写入CSV文件

python读取和写入csv文件

在 Python 中读取和写入 CSV 文件

Python - 使用 utf-8 编码读取和写入 csv 文件

python读取并写入csv文件

python如何根据csv中一列的内容对另一列进行写入