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')#输入文件夹路径即可
Python读取本地html文件内容块并给该文件重命名
最新推荐文章于 2024-10-27 11:29:42 发布
这段代码使用BeautifulSoup库解析HTML文件,读取文件的标题,然后将文件名改为去除非法字符后的标题。它遍历指定文件夹中的所有.html文件,对每个文件进行处理,并在遇到FileExistsError时继续下一个文件。程序在处理1000个文件后停止。
摘要由CSDN通过智能技术生成