简体   繁体   English

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

[英]Python Error in Reading Files using Aiofiles

Simple Problem statement.简单的问题陈述。 I want to read files asynchronously .我想异步读取文件。 My problem is when I try to read a file using aiofiles.open it just errors out with the cryptic messsage我的问题是当我尝试使用 aiofiles.open 读取文件时,它只是用神秘的消息出错

AttributeError: __enter_

The crux of the problem can be demonstrated with the following sample问题的症结可以用下面的例子来证明

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()  

the file gets created but I can't read the same file using aiofiles.该文件已创建,但我无法使用 aiofiles 读取同一个文件。

I have tried specifying encoding etc, but nothing helps.我试过指定编码等,但没有任何帮助。

What does this error mean?这个错误是什么意思?

The aiofiles.open context manager is meant to be used asynchronously ( async with ), in a coroutine. aiofiles.open上下文管理器旨在在协程中async with使用( async with )。 Standard synchronous context managers rely on __enter__ and __exit__ methods, while async context managers use methods named __aenter__ and __aexit__ , thus, an async with is necessary to call __aenter__ and __aexit__ , instead of __enter__ and __exit__ (which are not defined for aiofiles.open ):标准同步上下文管理器依赖于__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