社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

读取json文件时在条件语句python中处理keyerror

arousa yasser • 5 年前 • 1325 次点击  

因此,我正在读取两个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")
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40248
 
1325 次点击  
文章 [ 3 ]  |  最新文章 5 年前
Louis Saglio
Reply   •   1 楼
Louis Saglio    6 年前

使用 if 'File Size' not in data_current:

使用时 in python根据dict查看键,而不是值。

LexyStardust
Reply   •   2 楼
LexyStardust    6 年前

这个 if key in dict 方法可能适合您,但也值得了解 get() dict对象的方法。

您可以使用这个来尝试从字典中检索一个键的值,如果它不存在,它将返回一个默认值- None 默认情况下,或者您可以指定自己的值:

data = {"foo": "bar"}
fname= data.get("file_name")  # fname will be None
default_fname = data.get("file_name", "file not found")  # default_fname will be "file not found"

这在某些情况下是很方便的。您也可以将此长手书写为:

defalut_fname = data["file_name"] if "file_name" in data else "file not found" 

但我不喜欢把钥匙写那么多次!

reportgunner
Reply   •   3 楼
reportgunner    6 年前

您可以通过执行以下操作来检查字典中是否存在密钥 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
>>>