python合并多个json文件
作者:野牛程序员:2023-11-23 17:07:50python阅读 3293
使用Python合并多个JSON文件可以通过以下步骤完成:
import json
import glob
# 获取所有JSON文件的文件名
file_names = glob.glob('path/to/json/files/*.json')
# 存储合并后的数据
merged_data = []
# 逐个读取JSON文件并合并数据
for file_name in file_names:
with open(file_name, 'r', encoding='utf-8') as file:
data = json.load(file)
merged_data.extend(data)
# 将合并后的数据写入新的JSON文件
with open('path/to/output/merged.json', 'w', encoding='utf-8') as output_file:
json.dump(merged_data, output_file, ensure_ascii=False, indent=2)
# 提示合并完成
print('JSON文件合并完成。')请替换 'path/to/json/files/' 和 'path/to/output/merged.json' 为你实际的文件路径。这段代码将获取指定目录下所有JSON文件,逐个读取并将其数据合并到一个列表中,最后将合并后的数据写入新的JSON文件。
记得在使用之前备份数据,以防止意外情况。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:一年级排队问题解题方法+典型题型
- 下一篇:python取json值某个value
