aiofiles
File I/O support for asyncio in Python with async file objects and a thread pool for blocking calls.
Official Documentation ↗v25.1.0. Check the official docs for the latest API surface.Installation
pip install aiofilesMethods
No methods match this filter.
Overview
aiofiles wraps blocking file operations so asyncio applications can read and write without stalling the event loop. It mirrors the standard file object with awaitable methods.
Core Methods
Open with aiofiles.open and use async with, then await read, write, readline or readlines, and iterate lines with async for. Operations run in a thread pool internally.
Usage Notes
Use chunked reads for large files and always close with the async context manager. Combine with asyncio.gather carefully, since many concurrent file operations consume thread pool capacity.
Common Pitfalls
Reading whole files into memory on large inputs causes spikes. No async support for some file operations such as stat may require direct calls that block briefly. Thread pool limits bound real concurrency.
API reference evidence
Fetched from official sources on 2026-11-08T19:20:00+08:00 via WebFetch https://cdn.jsdelivr.net/gh/Tinche/aiofiles@latest/README.md;WebFetch https://cdn.jsdelivr.net/gh/Tinche/aiofiles@latest/src/aiofiles/threadpool/__init__.py(返回空,未取得 open 的 python 函数声明).
aiofiles.open→ signature from https://cdn.jsdelivr.net/gh/Tinche/aiofiles@latest/README.md; official text: “python async with aiofiles.open('filename', mode='r') as f: contents = await f.read() print(contents) 'My file contents'”file.read / file.write→ signature from https://cdn.jsdelivr.net/gh/Tinche/aiofiles@latest/README.md; official text: “In case of success, an asynchronous file object is returned with an API identical to an ordinary file, except the following methods are coroutines and delegate to an executor: -close-flush-isatty-read- `r”async iteration→ signature from https://cdn.jsdelivr.net/gh/Tinche/aiofiles@latest/README.md; official text: “Asynchronous iteration is also supported.python async with aiofiles.open('filename') as f: async for line in f: ...”
FAQ
- Does aiofiles make disk I/O truly non-blocking?
- It delegates operations to a thread pool, so the event loop is not blocked while the OS performs the work. The disk operation itself still runs on a thread, not natively async.
- When should I use aiofiles?
- Use it in asyncio services that otherwise block the loop on file operations. For small, infrequent reads it may not be worth the overhead compared to a direct read.
- How do I stream large files?
- Read in chunks with f.read(chunk_size) or iterate lines so the whole file is not loaded into memory, which matters for large uploads and logs.
Report a problem with this API docOpens a pre-filled issue on GitHub.