Python 错误:“属性错误:__enter__”

Cai*_*dre 5 python json enter

所以,我无法加载我的 json 文件,我不知道为什么,谁能解释我做错了什么?

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

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

    with open("commands/databases/cases.json", "r") as d:
AttributeError: __enter__
Run Code Online (Sandbox Code Playgroud)

a20*_*a20 20

我在这一行收到此错误:

with concurrent.futures.ProcessPoolExecutor as executor:
Run Code Online (Sandbox Code Playgroud)

缺少括号是问题所在

with concurrent.futures.ProcessPoolExecutor() as executor:
Run Code Online (Sandbox Code Playgroud)


Luk*_*raf 6

最有可能的是,您已将 Python内置open函数重新分配给代码中的其他内容(几乎没有其他合理的方式可以解释此异常)。

with然后该语句将尝试将其用作上下文管理器,并__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)
Run Code Online (Sandbox Code Playgroud)

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