2022-07-13 async异步协程操作文件

使用这个:anyio (https://github.com/agronholm/anyio)
如果是在fastapi框架里,无需另外安装
否则需要通过pip install anyio来安装
语法上类似标准库pathlib
大致用法如下:

import datetime
from anyio import Path

filepath = Path(__file__)
another = filepath.parent / 'sub_dirpath' / 'filename.ext'

if await another.exists():
    content = await another.read_bytes()
elif not await another.parent.exists():
    await another.parent.mkdir(parents=True)
else:
    await another.write_bytes(b'1')

# glob/stat/remove
async for p in filepath.parent.glob('*'):
    if await p.is_file():
        stat = await p.stat()
        create_time = datetime.fromtimestamp(stat.st_ctime)
        update_time = datetime.fromtimestamp(stat.st_mtime)
        await p.unlink()  # remove file
        print(f'{p} created at: {create_time}, modified at: {update_time}, removed at: {datetime.now()}')
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容