Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opening files in async-await functions python

Am using discord.py which requires using async-await functions. I want to dump and load data using pickle and JSON modules. but when trying that I get this error

AttributeError: __enter__
d:\Users\-------\visual studio projects\------------\main.py:65: RuntimeWarning: 
coroutine 'Command.__call__' was never awaited

I believe this happened because am opening the file inside and async-await function. so I tried an alternative way to open the files with async functions with aiofiles:

async with aiofiles.open("owners.pkl", mode="rb") as file:
    owner_dict = pickle.load(file)

but the problem is that pickle and json does work inside async functions.

Is there any alternative way to open, load, and dump with JSON or pickle inside async-await functions ???

like image 739
Zaid abuelbeh Avatar asked Oct 15 '25 06:10

Zaid abuelbeh


1 Answers

The thing returned by aiofiles.open is not a regular file-like object, its operations need to be awaited:

async with aiofiles.open("owners.pkl", mode="rb") as file:
    owner_dict = pickle.loads(await file.read())

Then again, this doesn't really help all that much since the deserialization will still happen in a blocking way (only reading the file will be async).


And a general note: Even if some interface demands an async function, there's no restriction on what happens inside of it. You can just write async in front of a normal, blocking function, and it will just work (without the benefits of async/await of course).

like image 76
L3viathan Avatar answered Oct 17 '25 20:10

L3viathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!