CSV的讀取與寫入

csv是常用的資料格式,因為是純文字檔操作方便,python可以使用csv模組來存取csv

函數說明
csv.reader(檔案)產生讀取csv物件,讀取形式為串列
csv.writer(檔案)產生寫入csv物件,讀取形式為串列
csv.DictReader(檔案) 產生讀取csv物件,讀取形式為字典
csv.DictWriter(檔案) 產生寫入csv物件,讀取形式為串字典
csv物件.writeheader()把定義好的欄位(fieldnames=)寫進去檔案
csv物件.writerow寫入一維串列或字典
csv物件.writerows 寫入二維串列或字典

下面四種方式可選擇一種方式建立csv

記得把模式”a”改成自己想要的

import csv
#第一種
with open("test3.csv", "w",encoding="utf-8-sig", newline="") as csvfile:
    #加入BOM用excel才不會亂馬
    name = ['number', 'name', 'Sit-ups(1m)', 'Push up(1m)', '3KM']
    #預先欄位
    writer_in = csv.DictWriter(csvfile, fieldnames=name)
    #定義欄位名稱
    writer_in.writeheader()
    #把欄位名稱寫入csv裡
    writer_in.writerow({'number': "001", 'name': 'Jeff', 'Sit-ups(1m)' : "50", "Push up(1m)" : "70", "3KM" : "12min"})
    #寫入一維串列
    writer_in.writerow({"number" : "002", "name" : "Alleb", "Sit-ups(1m)" : "60", "Push up(1m)" : "60", "3KM" : "16min"})
    writer_in.writerow({"number" : "003", "name" : "Joe", "Sit-ups(1m)" : "40", "Push up(1m)" : "50", "3KM" : "13min"})
    csvfile.write("--------no1--------")
    #依照字典值把元素帶進去

#第二種
with open("test3.csv", "a" ,encoding="utf-8-sig", newline="") as csvfile:
    writer_in = csv.writer(csvfile)
    writer_in.writerow(["number", "name", "Sit-ups(1m)", "Push up(1m)", "3KM"])
    writer_in.writerow(["001", "Jeff", "50", "70", "12min"])
    writer_in.writerow(["002", "Allen", "60", "60", "16min"])
    writer_in.writerow(["003", "Joe", "40", "50", "13min"])
    csvfile.write("--------no2-------")
    #每筆資料逐筆寫入

#第三種
datalist = [
    ["number", "name", "Sit-ups(1m)", "Push-up(1m)", "3KM"],
    ["001", "Jeff", "50", "70", "12min"],
    ["002", "Allen", "60", "60", "16min"],
    ["003", "Joe", "40", "50", "13min"]
]
with open("test3.csv", "a", encoding="utf-8-sig", newline="") as csvfile:
    writer_in = csv.writer(csvfile)
    writer_in.writerows(datalist)
    csvfile.write("--------no3--------")
    #寫入二維串列

#第四種
#先建字典
datadict = [
    {"number" : "001", "name" : "Jeff", "Sit-ups(1m)" : "50", "Push up(1m)" : "70", "3KM" : "12min"},
    {"number" : "002", "name" : "Allen", "Sit-ups(1m)" : "60", "Push up(1m)" : "60" , "3KM" : "16imn"},
    {"number" : "003", "name" : "Joe", "Sit-ups(1m)" : "40", "Push up(1m)" : "50", "3KM" : "13min"}
]
with open("test3.csv", "a", encoding="utf-8-sig", newline="") as csvfile:
    #定義欄位
    names = ['number', 'name', 'Sit-ups(1m)', 'Push up(1m)', '3KM']
    #將dictionary寫入檔案並使用定義好的標題欄位(names)
    writer_in = csv.DictWriter(csvfile, fieldnames=names)   #定義欄位名稱
    writer_in.writerows(datadict)   #寫入字典,須以list包住字典
    writer_in.writeheader()     #寫入欄位名稱(第一列)
    csvfile.write("--------no4(end)--------")

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *