aiofile
aiofile provides real asynchronous file operations for asyncio applications. It addresses the blocking nature of ordinary file I/O by delegating operations to a separate thread pool, ensuring that file operations do not block the asyncio event loop. The library is Apache2 licensed, currently at version 3.9.0, and maintains a stable development status.
Warnings
- gotcha The low-level `aiofile.AIOFile` object does not maintain an internal file pointer. When using `AIOFile` directly, you must explicitly pass the `offset` argument for each `read` or `write` operation. For a more standard file-like behavior with an implicit pointer, use the `aiofile.async_open` helper.
- gotcha The native Linux AIO implementation used by `aiofile` (via `caio`) cannot perform asynchronous operations on special file systems like `/proc/` or `/sys/`. Attempts to use `aiofile` on these file types may fail.
- gotcha When reading files line by line, especially with many small lines, repeatedly calling `await file_obj.readline()` on an `async_open` object can be suboptimal. Since version 3.7.0, `__aiter__` on an `async_open` object returns a `LineReader`, which is more efficient for line-based iteration.
- gotcha Using Python's built-in `open()` function or other synchronous file I/O operations directly within an `asyncio` application's event loop will block the entire loop, negating the benefits of asynchronous programming and potentially freezing your application.
Install
-
pip install aiofile
Imports
- async_open
from aiofile import async_open
- AIOFile
from aiofile import AIOFile
Quickstart
import asyncio
from aiofile import async_open
async def main():
# Write to a file asynchronously
async with async_open("hello.txt", mode="w+") as f:
await f.write("Hello, aiofile!")
await f.seek(0)
content = await f.read()
print(f"Read: {content}")
# Read a file line by line asynchronously
async with async_open("hello.txt", mode="r") as f:
async for line in f:
print(f"Line: {line.strip()}")
asyncio.run(main())