在Python中,我们可以使用json和os模块来比较和显示包含历史数据的多个JSON文件。下面是一个解决方法的代码示例:
import json
import os
def compare_json_files(file1, file2):
with open(file1, 'r') as f1, open(file2, 'r') as f2:
data1 = json.load(f1)
data2 = json.load(f2)
# 比较两个JSON文件的数据
if data1 == data2:
print(f"{file1} 和 {file2} 中的数据完全相同")
else:
print(f"{file1} 和 {file2} 中的数据不完全相同")
def display_json_files(folder):
for filename in os.listdir(folder):
if filename.endswith('.json'):
file_path = os.path.join(folder, filename)
with open(file_path, 'r') as f:
data = json.load(f)
print(f"{filename}:")
print(json.dumps(data, indent=4))
print()
# 比较两个JSON文件
compare_json_files('file1.json', 'file2.json')
# 显示文件夹中的所有JSON文件
display_json_files('data_folder')
在上述代码中,compare_json_files
函数用于比较两个JSON文件的数据是否相同。它使用json.load
函数将JSON文件中的数据加载为Python对象,然后使用==
运算符比较两个对象是否相同。
display_json_files
函数用于显示指定文件夹中所有JSON文件的内容。它使用os.listdir
函数列出文件夹中的所有文件,然后使用json.load
函数加载JSON文件的内容,并使用json.dumps
函数以漂亮的格式进行显示。
你可以根据自己的需求修改以上代码,并将文件路径和文件夹路径替换为你自己的路径。