阅界食谱今天吃什么,先来这里看看
代码片段

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() 会吃掉内存。

同类模板

Python 读写文件与 JSON · 阅界食谱