1

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?

Ajax1234
  • 69,937
  • 8
  • 61
  • 102
Saugat Mukherjee
  • 778
  • 8
  • 32

1 Answers1

4

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())
Ajax1234
  • 69,937
  • 8
  • 61
  • 102