利用python读取多个json文件
时间: 2023-12-07 18:37:52 浏览: 86
以下是利用Python读取多个JSON文件的示例代码:
import json
import os
# 定义要读取的JSON文件所在的文件夹路径
json_folder = "./json_files/"
# 定义一个空的字典,用于存储所有JSON文件中的数据
merged_data = {}
# 遍历所有的JSON文件,将数据合并到merged_data中
for file_name in os.listdir(json_folder):
if file_name.endswith(".json"):
file_path = os.path.join(json_folder, file_name)
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
# 如果有相同的键,只保留后读取的
merged_data.update(data)
# 将合并后的JSON数据写入到一个新的JSON文件中
with open("merged.json", "w", encoding="utf-8") as f:
json.dump(merged_data, f, ensure_ascii=False)
上述代码中,我们首先定义了要读取的JSON文件所在的文件夹路径,然后遍历该文件夹中的所有JSON文件,将它们的数据合并到一个空的字典中。如果有相同的键,我们只保留后读取的。最后,我们将合并后的JSON数据写入到一个新的JSON文件中。
相关推荐


















