Python读取本地html文件内容块并给该文件重命名

这段代码使用BeautifulSoup库解析HTML文件,读取文件的标题,然后将文件名改为去除非法字符后的标题。它遍历指定文件夹中的所有.html文件,对每个文件进行处理,并在遇到FileExistsError时继续下一个文件。程序在处理1000个文件后停止。
摘要由CSDN通过智能技术生成
from bs4 import BeautifulSoup as BS
import os

def file_rename(path):
    # 读 html文件 title,给该文件改名成 title。
    suffix = ".html"
    i = 1
    for file in os.listdir(path):
        try:
            if i != 1000:
                if file.endswith(suffix):
                    if os.path.isfile(os.path.join(path, file)):
                        soup = BS(open(os.path.join(path, file), encoding='utf-8'), features='html.parser')
                        if soup.title.string is None:
                            continue
                        else:
                            new_name = soup.title.string.replace(' ', '_').replace("|", "").replace("<", "").replace(
                                ">", "").replace("?", "").replace('"', "").replace('?', "").replace(':', "")//去掉非法符号
                            os.rename(os.path.join(path, file), os.path.join(path, new_name + suffix))
                            i = i + 1
                            print(i)
            else:
                break
        except FileExistsError:
            continue
    print("end!")


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    file_rename(r'D:\xxx')#输入文件夹路径即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值