Python 使用 Aiofiles 读取文件时出错
Python Error in Reading Files using Aiofiles
简单的问题陈述。我想异步读取文件。我的问题是,当我尝试使用 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 读取同一个文件。
我试过指定编码等,但没有任何帮助。
这个错误是什么意思?
aiofiles.open
上下文管理器旨在在协程中异步使用 (async with
)。标准同步上下文管理器依赖于 __enter__
和 __exit__
方法,而 async
上下文管理器使用名为 __aenter__
和 __aexit__
的方法,因此,async with
是有必要调用 aiofiles.open
的 __aenter__
和 __aexit__
方法,而不是 __enter__
和 __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())
简单的问题陈述。我想异步读取文件。我的问题是,当我尝试使用 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 读取同一个文件。
我试过指定编码等,但没有任何帮助。
这个错误是什么意思?
aiofiles.open
上下文管理器旨在在协程中异步使用 (async with
)。标准同步上下文管理器依赖于 __enter__
和 __exit__
方法,而 async
上下文管理器使用名为 __aenter__
和 __aexit__
的方法,因此,async with
是有必要调用 aiofiles.open
的 __aenter__
和 __aexit__
方法,而不是 __enter__
和 __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())