aiofiles根据特定条件异步删除文件夹中的文件

2024-04-25 01:26:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含大约50000个HTML文件的文件夹。 我正在尝试编写打开文件的脚本,若标题包含某些字符串,那个么文件应该被删除

这是我迄今为止的尝试:

import aiofiles
import glob
from natsort import natsorted
import asyncio
from bs4 import BeautifulSoup
import os

    async def main():
        i=0
        htmls = glob.glob("CarsPages" + "//*.html")
        for html in natsorted(htmls):
            async with aiofiles.open(html, mode='r', encoding='UTF-8',  errors='strict', buffering=1) as f:
                contents = await f.read()
                soup = BeautifulSoup(contents, features="lxml")
                if "Best portal" in soup.title.get_text():
                    i+=1
                    os.close(html) 
                    os.remove(html)
                    print("removing: ", html)
        print("Removed: ", i, " pages")
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

但我得到了:

os.close(html) TypeError: an integer is required (got type str)

不知道使用aiofiles打开后,关闭和删除要使用哪些函数

编辑-基于@joao answer的工作代码

import aiofiles
import glob
from natsort import natsorted
import asyncio
from bs4 import BeautifulSoup
import os

async def main():
    i=0
    htmls = glob.glob("CarsPages" + "//*.html")
    for html in natsorted(htmls):
        async with aiofiles.open(html, mode='r', encoding='UTF-8',  errors='strict', buffering=1) as f:
            contents = await f.read()
            soup = BeautifulSoup(contents, features="lxml")
        if "Best portal" in soup.title.get_text():
            i+=1
            os.remove(html)
            print("removed: ", html)
    print("Removed: ", i, " pages")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Tags: infromimportloopasyncioasyncosmain
1条回答
网友
1楼 · 发布于 2024-04-25 01:26:35

我假设您正在使用python>;=3.5,您使用aiofiles.open作为上下文管理器,因此您不必担心自己关闭文件。您需要做的是,当您的条件确定应该删除该文件时,只需退出上下文管理器块,然后在上下文管理器块之后删除该文件(是的,os.remove是作业的正确函数,只需确保不需要绝对路径)

不幸的是,您不能将break与上下文管理器一起使用,但是this question显示了实现相同结果的各种方法

相关问题 更多 >