Data File
CSV
CSV 檔案
l 什麼是CSV?
Ø CSV (Comma-Separated Values,逗號分隔值)為常⾒的⼀
種「純文字」資料儲存的檔案格式,將所有資料以半形的逗號
隔開,⼀般的試算表軟體均能處理並儲存CSV格式
Ø 例如健保署的「健保特約機構⼝罩剩餘數量明細清單」開放資
料格式提供的就是CSV檔,⽤Excel開啟的畫⾯如圖
Ø CSV檔可以⽤⼀般文字編輯軟體來開啟,例如⽤記事本開啟的
畫⾯如圖,無法像試算表軟體那樣對⿑
寫入 CSV 檔案
# 使⽤ csv module 來操作CSV檔
# [Link](), [Link]()
from pathlib import Path
import csv
data_points = [
[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18],
]
path = [Link]() / '[Link]'
# with [Link](mode='w', encoding='utf-8', newline='') as file:
# writer = [Link](file)
# for data_item in data_points:
# [Link](data_item)
with [Link](mode='w', encoding='utf-8', newline='') as file:
writer = [Link](file)
[Link](data_points)
讀取 CSV 檔案
# 使⽤ csv module 來操作CSV檔 .reader()
from pathlib import Path
import csv
data_points = []
path = [Link]() / '[Link]'
with [Link](mode='r', encoding='utf-8') as file:
reader = [Link](file) # return a list with str elements
for row in reader:
# convert elements of list from str to int
int_row = [int(value) for value in row]
# put int_row into data_points
data_points.append(int_row)
print(data_points)
讀取有標題的 CSV 檔案
# Change salary from str to float
def process_row(row):
row['salary'] = float(row['salary'])
return row
# 使⽤ csv module 中的 [Link] 來讀有標題的CSV
from pathlib import Path from pathlib import Path
import csv import csv
path = [Link]() / '[Link]' path = [Link]() / '[Link]'
with [Link](mode='r', encoding='utf-8') as file: with [Link](mode='r', encoding='utf-8') as file:
reader = [Link](file) reader = [Link](file)
header_row = [Link] header_row = [Link]
print('header row: ', header_row) print('header row: ', header_row)
print('contents: ') print('contents: ')
for row in reader: for row in reader:
print(row) print(process_row(row))
寫入有標題的 CSV 檔案
# 使⽤ csv module 中的 [Link] 來寫有標題的CSV
from pathlib import Path
import csv
people = [
{'name':'Jacky', 'age':50},
{'name':'Mary', 'age':45},
{'name':'Steven', 'age':30},
]
path = [Link]() / '[Link]'
with [Link](mode='w', encoding='utf-8', newline='')
as file:
writer = [Link](file, fieldnames = ['name','age'])
[Link]()
[Link](people)
#Lab
CSV file
• 請將上⽅list的內容,寫入[Link]當中
• 將[Link]的內容讀出到⼀個叫num的整數 list 中,印出num list的內容
• 請將上⽅csv檔案的內容,讀出來,並且印出header row 和csv content row
#Lab
Output highest score
讀取[Link]的姓名及分數,幫每個人算出最高成績,最後將最高成績寫入[Link]