pythonpython-asynciopython-aiofiles

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

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.

I have tried specifying encoding etc, but nothing helps.

What does this error mean?


Solution

  • The aiofiles.open context manager is meant to be used asynchronously (async with), in a coroutine. Standard synchronous context managers rely on __enter__ and __exit__ methods, while async context managers use methods named __aenter__ and __aexit__, thus, async with is necessary to call the __aenter__ and __aexit__ methods of aiofiles.open, instead of __enter__ and __exit__ (which are not defined for 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())