python 读写csv格式的文件

python在它的标准库中包含了csv模块。
例子环境 python3.4 win7 32位

1.读取csv文件
csvTest-data.csv内容如下:
ItemID,Name,Description,Owner,Borrower,DateLent,DateReturned
1,LawnMower,Small Hover mower,Fred,Joe,4/1/2012,4/26/2012
2,LawnMower,Ride-on mower,Mike,Anne,9/5/2012,1/5/2013
3,Bike,BMX bike,Joe,Rob,7/3/2012,7/22/2013
4,Drill,Heavy duty hammer,Rob,Fred,11/19/2013,11/29/2013
5,Scarifier,”Quality, stainless steel”,Anne,Mike,12/5/2013,
6,Sprinkler,Cheap but effective,Fred,,,

#csvTest.py
import csv

with open('E:\pyProjects\csvTest-data.csv') as f:
    datareader = csv.reader(f);
    print (list(datareader))

这里写图片描述

2.写入csv文件

#csvTest_write.py
import csv

items = [['1','LawnMower','Small Hover mower','Fred','$150','Excellent','2012-01-05'],['2','LawnMower','Ride-on mower','Mike','$370','Fair','2012-04-01'],['3','Bike','BMX bike','Joe','$200','Good','2013-03-22'],['4','Drill','Heavy duty hammer','Rob','$100','Good','2013-10-28'],['5','Scarifier','Quality, stainless steel','Anne','$200','2013-09-14'],['6','Sprinkler','Cheap but effective','Fred','$80','2014-01-06']]

with open('E:\pyProjects\csvTest-data2.csv','w',newline='') as data:
    writer = csv.writer(data)
    for item in items:
        writer.writerow(item)

执行后,生成csvTest-data2.csv文件
这里写图片描述

2016/08/09 21:29:00

你可能感兴趣的:(python)