You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用aiofiles异步读取文件时报AttributeError: __enter_错误该如何解决?

错误本质

你遇到的AttributeError: __enter__和文件权限、编码参数无关,根本原因是aiofiles.open返回的是异步上下文管理器,它仅实现了异步场景下的__aenter__/__aexit__魔法方法,没有实现普通同步上下文管理器要求的__enter__/__exit__方法。你用普通with关键字调用时,解释器会尝试调用对象的__enter__方法,找不到就抛出该错误。

同时aiofiles封装的文件操作方法(比如read/write)都是协程对象,调用时必须加await关键字才能拿到实际返回结果。

正确实现方案

异步操作必须遵循Python的异步语法规则,调整后的可运行代码如下:

import asyncio
import aiofiles

# 同步创建测试文件
with open("/tmp/test/abc_20211105.txt","w") as f:
    f.write("this is a sample!")

async def async_read_file():
    # 用async with调用异步上下文管理器
    async with aiofiles.open('/tmp/test/abc_20211105.txt','r', encoding='utf-8') as f:
        # 协程方法需要await触发执行
        content = await f.read()
        print(content) # 输出 this is a sample!

if __name__ == "__main__":
    # Python 3.7+ 可直接用asyncio.run运行异步入口函数
    asyncio.run(async_read_file())

    # Python 3.6及更早版本替换为以下代码:
    # loop = asyncio.get_event_loop()
    # loop.run_until_complete(async_read_file())
    # loop.close()

内容的提问来源于stack exchange,提问作者Saugat Mukherjee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:54:05