用 aiofiles 模块的 asyncio.to_thread() 方法将同步文件操作转换为异步操作

import aiofiles
import re
 async def download_text_to_file(url, name):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            text = await response.text()
            obj_content = re.compile(r"content: '(.*?)';", re.S)
            content = obj_content.search(text).group(1)
            content = name + "\n" + content
            async with aiofiles.open(name, mode="w") as f:
                await asyncio.to_thread(f.write, content)

你可能感兴趣的:(python)