首页 > 代码库 > python之读取和写入csv文件

python之读取和写入csv文件

写入csv文件源码:


 1 #输出数据写入CSV文件
 2 import csv
 3 data =http://www.mamicode.com/ [
 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文件