美文网首页
2022-07-13 async异步协程操作文件

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

作者: waketzheng | 来源:发表于2022-07-12 01:07 被阅读0次

    使用这个: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()}')
    

    相关文章

      网友评论

          本文标题:2022-07-13 async异步协程操作文件

          本文链接:https://www.haomeiwen.com/subject/xzdzbrtx.html