问题库 Python how-to

Python 如何读取和写入 JSON 文件

快速答案

用 json.load 读取,json.dump 写入,并指定 ensure_ascii=False 保留中文。

py
import json
with open('data.json', encoding='utf-8') as f:
    data = json.load(f)
with open('out.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

使用要点

  • 先用小样本确认字段、编码和空值,再处理完整数据。
  • 写出文件前确认分隔符、日期格式和中文编码,避免后续工具打不开。

相关内容