python 讀寫csv格式的檔案
阿新 • • 發佈:2019-01-01
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