Python错误:“AttributeError:__ enter __”

问题描述 投票:0回答:1

所以,我无法加载我的json文件,我不知道为什么,任何人都可以解释我做错了什么?

async def give(msg, arg):
    if arg[0] == prefix + "dailycase":
                with open("commands/databases/cases.json", "r") as d:
                     data = json.load(d)

出于某种原因,我收到此错误:

    with open("commands/databases/cases.json", "r") as d:
AttributeError: __enter__
python json enter
1个回答
1
投票

最有可能的是,你已经将Python builtin open function重新分配给了代码中的其他内容(几乎没有其他合理的方法可以解释这个异常)。

然后with语句将尝试将其用作context manager,并在首次进入__enter__区块时尝试调用其with方法。这会导致您看到的错误消息,因为您的对象称为open,无论它是什么,都没有__enter__方法。


在Python模块中查找要重新分配open的位置。最明显的是:

  • 全局范围内的函数,如def open(..)
  • 使用open =直接重新分配
  • 进口如from foo import openimport something as open

该函数最可能是可疑的,因为看起来你的open实际上是一个可调用的。

为了帮助您找到open意外绑定的对象,您也可以尝试

print('open is assigned to %r' % open)

在你的with声明之前。如果它没有说<built-in function open>,你就找到了你的罪魁祸首。

© www.soinside.com 2019 - 2024. All rights reserved.