问题库 Python how-to

Python 如何把 CSV 转 JSON

快速答案

用 csv.DictReader 读取表头,再 json.dump 输出数组。

py
import csv, json
with open('users.csv', newline='', encoding='utf-8') as f:
    rows = list(csv.DictReader(f))
with open('users.json', 'w', encoding='utf-8') as f:
    json.dump(rows, f, ensure_ascii=False, indent=2)

使用要点

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

相关内容