aiofiles并发读文件不快的主因是其依赖线程池模拟异步I/O,非内核级异步;默认线程数少、频繁调度开销大,大文件需分块读防OOM,Windows下路径编码易出错,须统一encoding和路径格式。

直接用 aiofiles 配合 asyncio.gather 并发读取多个文件是可行的,但默认行为容易卡在系统调用上,实际并发度可能远低于预期——根本原因在于 aiofiles 底层仍依赖线程池模拟异步 I/O,不是真正的内核级异步文件操作。
为什么 aiofiles 读文件经常“不快”甚至比同步还慢
aiofiles 的 open() 实际把 open()、read() 等阻塞调用丢进 asyncio.to_thread()(或旧版 loop.run_in_executor)里执行。这意味着:
- 每个文件读取都独占一个线程池线程,线程数默认只有
min(32, os.cpu_count() + 4),大量小文件时容易挤占线程资源 - 频繁创建/调度线程带来额外开销,尤其当文件数 > 50 且单个文件 concurrent.futures.ThreadPoolExecutor 显式控制
- 无法利用 Linux 的
io_uring或 Windows 的 IOCP,纯属“伪异步”
正确写法:用 asyncio.to_thread 包裹内置 open,而非依赖 aiofiles.open
绕过 aiofiles 的封装层,自己控制线程池复用和参数,更轻量、更可控:
import asyncio <p>async def read_file(path: str) -> str:</p><h1>直接用内置 open + to_thread,避免 aiofiles 的额外封装开销</h1><pre class="brush:php;toolbar:false;">return await asyncio.to_thread(open, path, "r", encoding="utf-8")
async def read_multiple_files(paths: list[str]) -> list[str]:
并发触发所有读取任务
tasks = [read_file(p) for p in paths]
results = await asyncio.gather(*tasks)
# 注意:这里拿到的是 file 对象,需再调 .read()
contents = await asyncio.gather(*[r.read() for r in results])
# 别忘了关闭
for f in results:
f.close()
return contents
更稳妥的做法是把 open + read + close 封装成原子操作:
async def read_file_content(path: str) -> str:
return await asyncio.to_thread(lambda: open(path, "r", encoding="utf-8").read())
这样省去手动 close,也避免忘记释放句柄。
大文件场景必须加 size 限制和分块读取
无论用哪种方式,并发读大文件(> 10MB)极易触发内存暴涨甚至 OOM。不能直接 .read():
-
aiofiles的f.read()默认读全部内容到内存,无流式支持 -
asyncio.to_thread中的open().read()同样全加载 - 真正安全的做法是限定单次读取大小,例如每次读 64KB:
async def read_file_chunked(path: str, chunk_size: int = 65536) -> bytes:
def _read_chunks():
with open(path, "rb") as f:
while chunk := f.read(chunk_size):
yield chunk
# 转成 list 一次性获取所有 chunk,或用 async generator(需额外适配)
return b"".join(await asyncio.to_thread(list, _read_chunks()))
若需边读边处理(如解析 JSON 行、计算哈希),应改用同步迭代器 + to_thread 分批提交,而非试图“异步流式读”。
Windows 下路径与编码的隐藏坑
在 Windows 上,以下两点极易导致 UnicodeDecodeError 或 FileNotFoundError:
- 路径含中文或特殊符号时,
aiofiles.open()在某些版本会错误地 double-encode 路径,建议统一用pathlib.Path.resolve()标准化后再传入 - 未显式指定
encoding参数时,aiofiles可能用系统默认编码(如 cp936),而asyncio.to_thread(open(...))则跟随 Python 默认(utf-8),行为不一致 - 绝对路径开头的
\?前缀(用于绕过 MAX_PATH 限制)不被aiofiles支持,但原生open()支持
所以,跨平台项目中建议始终显式写 encoding="utf-8",并用 pathlib.Path(path).resolve().as_posix() 统一路径格式。
真正影响并发效率的从来不是语法糖,而是线程池大小、文件大小分布、系统页缓存命中率和编码一致性——这些细节没对齐,再多的 async/await 也只是在排队等锁。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











