Python 讀寫文件與 JSON
最常用的文件讀寫,注意編碼和路徑。
範本正文
import json
from pathlib import Path
p = Path("data/items.json")
# 讀 JSON(一定要指定 encoding,否則中文在 Windows 上會亂碼)
data = json.loads(p.read_text(encoding="utf-8"))
# 寫 JSON(ensure_ascii=False 保留中文,indent 方便 diff)
p.write_text(
json.dumps(data, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
# 逐行讀大文件(不要 read() 整個文件)
with p.open(encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
yield_obj = json.loads(line)怎麼用
處理數據腳本時的基礎片段。
使用要點
- 寫 JSON 一定加 ensure_ascii=False,否則中文會變成 \uXXXX。
- 讀大文件用逐行迭代,一次性 read() 會吃掉內存。