1

简单的问题陈述。我想异步读取文件。我的问题是当我尝试使用 aiofiles.open 读取文件时,它只是出现了神秘的消息错误

AttributeError: __enter_

问题的症结可以用下面的例子来证明

with open("/tmp/test/abc_20211105.txt","w") as f:
    f.write("this is a sample!")
with aiofiles.open('/tmp/test/abc_20211105.txt','r') as f: # This is where the error occurs
    f.read()  

该文件已创建,但我无法使用 aiofiles 读取相同的文件。

我试过指定编码等,但没有任何帮助。

这个错误是什么意思?

4

1 回答 1

3

aiofiles.open上下文管理器旨在在协程中异步使用 ( ) async with。标准同步上下文管理器依赖于__enter__and__exit__方法,而async上下文管理器使用名为__aenter__and的方法__aexit__,因此async with有必要调用 的__aenter__and__aexit__方法aiofiles.open,而不是__enter__and __exit__(未定义aiofiles.open):

import asyncio
async def read_files():
   async with aiofiles.open('/tmp/test/abc_20211105.txt','r') as f:
      await f.read() 

asyncio.run(read_files())
于 2021-11-05T15:11:26.800 回答