讀檔(七):從多種檔案中抓取與整合資料
透過前幾週的分享,我們已經學會了 Python 中三種最常見的讀檔方式:
txt:純文字檔
csv:表格型資料
json:巢狀結構資料
在真實的工作或專案中,我們常常需要同時處理不同格式的資料,
然後把它們「整合」成一份完整報告。
今天就讓我們一起實際整合看看吧~
實戰情境:整合學生成績資料
假設我們現在在做一個「學生成績整合系統」。
有三個不同來源的檔案:
students.txt:學生名單
score.csv:各科分數
meta.json:課程資訊
students.txt
Jerry
Sally
Momo
score.csv
name,math,english
Jerry,95,88
Sally,87,90
Momo,100,93
meta.json
{
“course”: “stanCode SC101”,
“teacher”: “Jerry Liao”,
“semester”: “2025 Spring”
}
以上是我們目前有的檔案及內容
Step 1:讀取文字檔
with open(‘students.txt’, ‘r’) as f:
students = [line.strip() for line in f]
print(students)
輸出結果:
[‘Jerry’, ‘Sally’, ‘Momo’]
Step 2:讀取 CSV 檔
import csv
with open(‘score.csv’, ‘r’) as f:
reader = csv.DictReader(f) # 可以自動把每一行轉成字典的絕招
for row in reader:
scores[row[‘name’]] = {‘math’: int(row[‘math’]), ‘english’: int(row[‘english’])}
print(students)
輸出結果:
{ ‘Jerry’: {‘math’: 95, ‘english’: 88},
‘Sally’: {‘math’: 87, ‘english’: 90},
‘Momo’: {‘math’: 100, ‘english’: 93} }
Step 3:讀取 JSON 檔
import json
with open(‘meta.json’, ‘r’) as f:
meta = json.load(f)
print(meta)
輸出結果:
{‘course’: ‘stanCode SC101’, ‘teacher’: ‘Jerry Liao’, ‘semester’: ‘2025 Spring’}
Step 4:整合資料
現在我們可以把三種資料結合成一份完整的成績報告!
report = {
“course_info”: meta,
“students”: []
}
for name in students:
info = {
“name”: name,
“math”: scores[name][‘math’],
“english”: scores[name][‘english’],
“average”: (scores[name][‘math’] + scores[name][‘english’]) / 2
}
report[“students”].append(info)
print(report)
輸出結果:
{
‘course_info’: {‘course’: ‘stanCode SC101’, ‘teacher’: ‘Jerry Liao’, ‘semester’: ‘2025 Spring’},
‘students’: [
{‘name’: ‘Jerry’, ‘math’: 95, ‘english’: 88, ‘average’: 91.5},
{‘name’: ‘Sally’, ‘math’: 87, ‘english’: 90, ‘average’: 88.5},
{‘name’: ‘Momo’, ‘math’: 100, ‘english’: 93, ‘average’: 96.5}
]
}
Step 5:把結果輸出成 JSON 報告
with open(‘final_report.json’, ‘w’) as f:
json.dump(report, f, ensure_ascii=False, indent=4)
這樣,我們就可以把 .txt、.csv、.json 三種不同來源的資料整合起來,
並匯出成一個漂亮的 JSON 成績報告檔囉!
小比喻
| 類型 | 比喻 | 角色 |
|---|---|---|
.txt |
📋 學生清單 | 誰要被統計 |
.csv |
📊 成績表 | 分數資料來源 |
.json |
🗂️ 課程資訊 | 額外描述資料 |
三者合起來,就像把學生名單、成績表、課程說明書組合成一份完整的成績冊。
stanCode標準程式教育機構-你也值得更好的教育
Facebook|https://www.facebook.com/stancode.tw
Instagram|https://www.instagram.com/stancode_tw/
YouTube|https://www.youtube.com/@stancode7228/videos
Website|https://www.stancode.tw/
TikTok|https://www.tiktok.com/@standardcoding
