微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python 异步写入文件

# -*- coding:utf-8 -*-
import asyncio
import aiofiles
import time
#异步操作时,函数名前必须加上async
async def func1():
#异步写入文件
async with aiofiles.open("text.txt","w",encoding="utf-8") as f:
await f.write("hello func1!\n")
print("func1数据写入成功")

async def func2():
async with aiofiles.open("text.txt","a",encoding="utf-8") as f:
await f.write("hello func2!\n")
print("func2数据写入成功")
#把多个任务加入列表
async def main():
tasks = [
func1(),
func2()
]
await asyncio.wait(tasks)

if __name__ == "__main__":
t1=time.time()
asyncio.run(main())
t2=time.time()
print(t2-t1)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐