繁体   English   中英

使用 Aiofiles 读取文件时出现 Python 错误

[英]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使用( async with )。 标准同步上下文管理器依赖于__enter____exit__方法,而异步上下文管理器使用名为__aenter____aexit__方法,因此, async with是调用__aenter____aexit__ ,而不是__enter____exit__ (未为aiofiles.open定义) :

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM