
👉 项目官网:https://www.python-office.com/ 👈

大家好,这里是程序员晚枫,正在all in AI编程实战。
今天教你怎么处理两种最常用的数据格式:JSON 和 CSV。
1、JSON是什么?
JSON 是网页开发常用的数据格式,类似这样:
1 2 3 4 5 6 7 8 9
| { "name": "张三", "age": 18, "skills": ["Python", "JavaScript"], "address": { "city": "重庆", "district": "渝北区" } }
|
2、读取JSON文件
1 2 3 4 5 6 7 8
| import json
with open('data.json', 'r', encoding='utf-8') as f: data = json.load(f)
print(data) print(data['name'])
|
3、写入JSON文件
1 2 3 4 5 6 7 8 9 10 11 12 13
| import json
data = { 'name': '李四', 'age': 25, 'skills': ['Python', '数据分析'] }
with open('output.json', 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4)
print('JSON写入完成!')
|
4、CSV是什么?
CSV 是逗号分隔值,类似 Excel 的纯文本版本:
1 2 3 4
| 姓名,年龄,城市 张三,18,重庆 李四,20,北京 王五,22,上海
|
5、读取CSV文件
1 2 3 4 5 6 7 8
| import csv
with open('data.csv', 'r', encoding='utf-8') as f: reader = csv.reader(f) for row in reader: print(row)
|
6、写入CSV文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import csv
data = [ ['姓名', '年龄', '城市'], ['张三', 18, '重庆'], ['李四', 20, '北京'], ['王五', 22, '上海'] ]
with open('output.csv', 'w', encoding='utf-8', newline='') as f: writer = csv.writer(f) writer.writerows(data)
print('CSV写入完成!')
|
7、实战案例:JSON转Excel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import json import office
def json_to_excel(json_file, excel_file): """JSON文件转Excel""" with open(json_file, 'r', encoding='utf-8') as f: data = json.load(f) if isinstance(data, list): rows = data else: rows = [data] if rows: headers = list(rows[0].keys()) table = [headers] for row in rows: table.append([row.get(h, '') for h in headers]) office.excel.write(path=excel_file, data=table) print(f'已转换:{excel_file}')
json_to_excel('data.json', 'output.xlsx')
|
8、实战案例:Excel转JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import json import office
def excel_to_json(excel_file, json_file): """Excel文件转JSON""" df = office.excel.read(path=excel_file) data = df.to_dict(orient='records') with open(json_file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4) print(f'已转换:{json_file}')
excel_to_json('data.xlsx', 'output.json')
|
9、常见问题
Q:中文乱码?
A:确保打开文件时指定 encoding='utf-8'。
Q:JSON里有特殊字符?
A:用 ensure_ascii=False 可以保留中文。
Q:CSV有引号问题?
A:读写时用 newline='' 参数可以避免。
10、下讲预告
学会了JSON和CSV,下一讲我们学 综合实战3:做一个通讯录管理系统。
敬请期待!
有问题欢迎加微信 python-office 进群交流~
程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。
🎓 AI 编程实战课程
想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!