gpt4 book ai didi

python - 读取json文件时处理条件语句python中的KeyError

转载 作者:行者123 更新时间:2023-11-28 17:02:23 29 4
gpt4 key购买 nike

所以我正在阅读两个 json 文件来检查 key 文件名和文件大小是否存在。在其中一个文件中,我只有 key 文件名,没有文件大小。当运行我的脚本时,它会一直通过 KeyError ,我想让它打印出没有 key 文件大小的文件名。

我得到的错误是:

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")

最佳答案

您可以通过执行 if 'File Size' not in data_current:

检查字典中是否存在键
>>> data = {"File Size": 200} # Dictionary of one value with key "File Size"
>>> "File Size" in data # Check if key "File Size" exists in dictionary
True
>>> "File Name" in data # Check if key "File Name" exists in dictionary
False
>>>

关于python - 读取json文件时处理条件语句python中的KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53554483/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com