aiofiles文件异步读写库用法-第二期
tornado吧
全部回复
仅看楼主
level 5
### 分块读取超大文件
.
CHUNK_SIZE = 1024
chunk_data = None
.
async with aiofiles.open(bigfile_path, mode=mode) as bigf:
  while True:
    chunk_data = await bigf.read(CHUNK_SIZE)
    if not chunk_data:
      break
.
    use_data(chunk_data)
.
.
.
.
总结核心调用:
1. while True:死循环
2. await bigf.read函数传入“本次读取操作读取的字节数上限”
3. if not chunk_data: break当读取到的字节数量为0时,表示读取到EOF,即整个文件都已被读完了,可结束循环
2025年12月07日 16点12分 1
level 5
### 并发执行多个写文件协程函数
.
tasks = [
  async_read_write_login_log_file(),
  async_read_write_user_operation_log_file(),
  async_read_write_request_log_file(),
]
.
await asyncio.gather(*tasks)
.
.
.
.
总结核心调用:
1. asyncio.gather函数传参格式是“每个task单独作为一个argument”
  1.1 这个语法导致它虽然支持不固定数量的task参数,但是“传入哪些task对象”必须在开发时确定
2. 通过定义tasks列表,然后向asyncio.gather传参时用*tasks语法,使得“传入哪些task对象”这个问题延迟到运行时才确定
2025年12月07日 16点12分 2
1