你的資料越來越多,list 和 dict 有點不夠用了? 別擔心,這一集我們來學會「怎麼把資料存得更漂亮、讀得更有效率」。
1️⃣ JSON 是什麼?為什麼大家都愛它?
JSON(JavaScript Object Notation)是一種常見的「資料交換格式」, 它長得很像 Python 的 dict,也能存 list,而且跨平台都能讀得懂,超萬用。📌 適合存「巢狀資料」或「設定檔」,例如人物角色、產品資訊、聊天記錄等。
✅ 寫入 JSON 檔
import json
person = {"name": "Joe", "age": 7, "hobbies": ["reading", "soccer"]}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(person, f, ensure_ascii=False, indent=2)
🔽 執行後會產生漂亮的 JSON 檔,內容像這樣:
{
"name": "Joe",
"age": 7,
"hobbies": [
"reading",
"soccer"
]
}
✅ 讀取 JSON 檔
with open("data.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["name"])
🔽 輸出:
Joe
2️⃣ CSV 表格:像 Excel 的好朋友
CSV(Comma-Separated Values)是一種用逗號分隔欄位的文字格式, 你可以把它想像成「純文字版的 Excel」。非常適合用來儲存名單、成績表、帳務資料。
範例內容:
姓名,年齡,分數
Joe,7,88
May,8,92
✅ 讀取 CSV
import csv
with open("grades.csv", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)
🔽 輸出:
['姓名', '年齡', '分數']
['Joe', '7', '88']
['May', '8', '92']
✅ 寫入 CSV
with open("grades.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["姓名", "年齡", "分數"])
writer.writerow(["Joe", 7, 88])
writer.writerow(["May", 8, 92])
🔽 執行後會產出一個 grades.csv
,可以用 Excel 開啟!
3️⃣ 自製小資料庫:不學 SQL 也能存資料
想存使用者紀錄、遊戲狀態或筆記內容,又還不想學 SQL? 你可以用 Python 的 dict 搭配 json 檔案,自製小型資料庫:
import json
# 模擬資料庫
data = {}
data["joe"] = {"score": 88, "age": 7}
# 儲存
with open("db.json", "w", encoding="utf-8") as f:
json.dump(data, f)
# 讀回來使用
with open("db.json", "r", encoding="utf-8") as f:
db = json.load(f)
print(db["joe"]["score"])
🔽 輸出:
88
🔸「db.json
就像一個模擬資料庫」,並說明如何透過 json.load()
將資料取回並操作。
🔸這樣你就可以把資料「記起來」,下次開啟程式還能繼續使用!
✅ 如何新增或修改資料庫內容
# 新增一筆使用者資料
db["may"] = {"score": 92, "age": 8}
# 修改已存在使用者的分數
db["joe"]["score"] = 90
# 刪除使用者資料
if "may" in db:
del db["may"]
# 列出所有使用者與分數
for user, info in db.items():
print(f"{user} 的分數是 {info['score']}")
# 儲存回資料庫檔案
with open("db.json", "w", encoding="utf-8") as f:
json.dump(db, f, ensure_ascii=False, indent=2)
🔽 說明:
- 你可以像操作 dict 一樣新增 key 或修改內部欄位,然後再用
json.dump()
寫回檔案,達成「資料庫更新」的效果。 del db["may"]
可以刪除指定使用者資料(記得先檢查是否存在)db.items()
讓你能走訪整個資料庫,列出每個使用者的資訊- 最後仍需使用
json.dump()
把資料存回檔案中 del db["may"]
可以刪除指定使用者資料(記得先檢查是否存在)db.items()
讓你能走訪整個資料庫,列出每個使用者的資訊- 最後仍需使用
json.dump()
把資料存回檔案中python
4️⃣ 小結:我該用哪一種?
