09 路徑與檔案讀寫
在 Colab 開啟 下載 Notebook · 下載 .py
要保留或交換程式的結果時,先選一種資料格式。文字檔適合逐行紀錄,CSV 適合表格,JSON 適合含有鍵和值的結構化資料。先備知識是常用容器與錯誤與例外。
路徑與 UTF-8
Path 表示路徑。用 folder / "report.txt" 組合資料夾和檔名。相對路徑從目前工作目錄開始。Colab 左側的「檔案」可檢查所在位置。本章用 TemporaryDirectory() 在每次執行建立獨立的資料夾,離開區塊後會清理。
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
report = Path(folder) / "report.txt"
report.write_text("資料已核對\n共 3 筆\n", encoding="utf-8")
lines = report.read_text(encoding="utf-8").splitlines()
print(lines[0])
print("行數", len(lines))
預期輸出
資料已核對
行數 2
指定 encoding="utf-8" 可以明確告訴 Python 如何解讀文字。write_text() 會覆寫同名檔案。若只想追加,使用 with path.open("a", encoding="utf-8") as handle:,並在寫入內容中明確加入換行。
讀 CSV 並檢查表頭
csv.DictReader 用表頭當作欄名。讀進來的欄值通常是字串,計算前先轉型。搭配 newline="",讓 csv 模組處理列與換行規則。以下函式需要 task 與 minutes 兩欄。
import csv
from pathlib import Path
from tempfile import TemporaryDirectory
def total_minutes(path):
with path.open(encoding="utf-8-sig", newline="") as handle:
rows = csv.DictReader(handle)
if sorted(rows.fieldnames or []) != ["minutes", "task"]:
raise ValueError("CSV 必須包含 task 與 minutes")
return sum(int(row["minutes"]) for row in rows)
with TemporaryDirectory() as folder:
path = Path(folder) / "work-log.csv"
path.write_text("task,minutes\n整理,15\n核對,25\n", encoding="utf-8")
print("合計", total_minutes(path))
path.write_text("task,minutes\n", encoding="utf-8")
print("只有表頭", total_minutes(path))
path.write_text("task,hours\n整理,1\n", encoding="utf-8")
try:
total_minutes(path)
except ValueError as error:
print(error)
預期輸出
合計 40
只有表頭 0
CSV 必須包含 task 與 minutes
utf-8-sig 可讀取含 UTF-8 BOM 的檔案。若根本沒有檔案,開啟時會先出現 FileNotFoundError。表頭正確時,還要按問題驗證每列的值,例如分鐘數的格式和範圍。
以 JSON 保存設定
json.dump() 和 json.load() 分別負責寫入與讀取。ensure_ascii=False 讓中文在檔案中保持可閱讀的形式。下例把字典存成設定檔再讀回。
import json
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
settings_path = Path(folder) / "settings.json"
with settings_path.open("w", encoding="utf-8") as handle:
json.dump({"工作類型": "校對", "提醒分鐘": 20}, handle, ensure_ascii=False)
with settings_path.open(encoding="utf-8") as handle:
settings = json.load(handle)
print(settings["工作類型"], settings["提醒分鐘"])
預期輸出
校對 20
練習
- 將兩行備註寫入 UTF-8 文字檔,讀回並印出第二行。
- 建立只含表頭的 CSV 和缺少檔案的路徑。使用本章的函式分別驗證合計為 0,以及檔案不存在時的訊息。
note_lines = ["開始核對", "已全部核對"]
empty_csv = "task,minutes\n"
# 用 TemporaryDirectory 建立練習檔,再呼叫 total_minutes()。
print("確認文字、空表格與缺檔的結果。")
預期輸出
確認文字、空表格與缺檔的結果。
參考解答
展開參考解法
本練習沿用上方的 total_minutes()。缺檔時捕捉 FileNotFoundError,不需把缺檔當成空表格。
with TemporaryDirectory() as folder:
directory = Path(folder)
notes = directory / "notes.txt"
notes.write_text("開始核對\n已全部核對\n", encoding="utf-8")
print(notes.read_text(encoding="utf-8").splitlines()[1])
work_log = directory / "empty.csv"
work_log.write_text("task,minutes\n", encoding="utf-8")
print(total_minutes(work_log))
try:
total_minutes(directory / "missing.csv")
except FileNotFoundError:
print("找不到紀錄檔")
預期輸出
已全部核對
0
找不到紀錄檔