我有一个for循环,循环遍历两个json文件中的值并比较它们。当我打印出这些值时,我正在检查键“File Name”在两个文件之间是否匹配。数据顺序已交换,但值相同。他们没有改变。你知道吗
dave.json has a match
emhy.json has no match
same.json has no match
我曾尝试使用sorted()
按升序打印出来,但似乎仍然不起作用。我的JSON文件如下:
day.json
{"File Name": "dave.json", "File Size": 2800}
{"File Name": "same.json", "File Size": 600}
{"File Name": "emhy.json", "File Size": 600}
night.json
{"File Name": "dave.json", "File Size": 2800}
{"File Name": "emhy.json", "File Size": 600}
{"File Name": "same.json", "File Size": 600}
值的顺序仍然相同。我的代码如下:
def compare_files():
with open('day.json', 'r') as current_data_file, open('night.json',
'r') as pre_data_file:
for current_data, previous_data in zip(current_data_file, pre_data_file):
data_current = json.loads(current_data)
data_previous = json.loads(previous_data)
sorted_previous = sorted(data_previous.items() , key = lambda t: t[0])
sorted_current = sorted(data_current.items(), key=lambda t: t[0])
current_fn = data_current['File Name']
previous_fn = data_previous['File Name']
if sorted_previous == sorted_current:
print (str(sorted_previous) + " has a match \n")
elif sorted_previous != sorted_current:
print (str(sorted_previous) + " has no match \n")
result = compare_files()
第一个问题-你的日期.json以及夜晚.json不是json文件,即使名称表明它们是。你知道吗
由于第一个问题,您无法直接加载它们。您可以按键分别加载和排序每一行,并与另一个文件中的相应行进行比较“文件名”总是在“文件大小”之前。如果顺序不同夜晚.json以及日期.json文件你来与不正确的结果。你知道吗
第三个问题是在新数据中查找文件,而不是在旧数据中查找。如果旧文件中有文件,而新文件中缺少该怎么办?你知道吗
如果文件是这种格式的,我会这样做
你知道吗日期.json你知道吗
你知道吗夜晚.json你知道吗
python代码
输出
相关问题 更多 >
编程相关推荐