How to use asyncio to read and write a file?

1 answer 1

Asynchronously in any way, but it is possible in executor.

import asyncio def read_file(file_name): return open(file_name).read() async def main(): loop = asyncio.get_event_loop() data = await loop.run_in_executor(None, read_file, 'data.txt') print(data) loop = asyncio.get_event_loop() loop.run_until_complete(main()) 
  • If there is a great desire, then you can find an asynchronous platform-specific API for regular files (for example, overlapped IO on Windows), although in the vast majority of cases the synchronous API using the cache is sufficient (asynchronous API or broken or less effective). - jfs