因此,我正在读取两个json文件,以检查密钥文件名和文件大小是否存在。在其中一个文件中,我只有密钥文件名,而没有文件大小。当运行我的脚本时,它会出现一个keyerror,我想让它打印出没有密钥文件大小的文件名。
我得到的错误是:
if data_current['File Size'] not in data_current:
KeyError: 'File Size'
file1.json
{"File Name": "personDetails.json Exists", "File Size": "7484"}
{"File Name": "agent.json Not Exists"}
file2.json
{"File Name": "personDetails.json Exists", "File Size": "7484"}
{"File Name": "agent.json Not Exists", "File Size": "9484"}
我的代码如下:
with open('file1.json', 'r') as f, open('file2.json', 'r') as g:
for cd, pd in zip(f, g):
data_current = json.loads(cd)
data_previous = json.loads(pd)
if data_current['File Size'] not in data_current:
data_current['File Size'] = 0
if data_current['File Name'] != data_previous['File Name']: # If file names do not match
print " File names do not match"
elif data_current['File Name'] == data_previous['File Name']: # If file names match
print " File names match"
elif data_current['File Size'] == data_previous['File Size']: # If file sizes match
print "File sizes match"
elif data_current['File Size'] != data_previous['File Size']: #
print "File size is missing"
else:
print ("Everything is fine")