我经常有包含10-20个HTML文件的文件夹需要更新。现在,我在一个文本编辑器中打开每个文件,并对每个文件使用5-10次查找和替换。
如何在所有20个文件中搜索X,如果找到X,则将其替换为Y?
发布于 2021-09-23 09:51:08
一个简单的解决方案是首先创建一个列表,其中包含您尝试更改的所有文件的位置,例如使用glob:
import os
import glob
base_directory = os.path.join('your', 'path', 'here')
all_html_files = glob.glob(base_directory + '*.html', recursive=True)现在,有了这个列表,您就可以简单地遍历它并分别对每个文件进行操作:
for file in all_html_files:
with open(file, 'r') as f:
raw_file = f.read()
# do your replacing here
processed_file = raw_file.replace('foo', 'bar')
with open(file, 'w') as f:
f.write(processed_file)发布于 2021-09-23 10:06:35
如果您使用的是python3.4或更高版本,则可以使用pathlib内置模块执行此任务,如下所示
import pathlib
for p in pathlib.Path("<path_to_your_dir_here>").rglob("*.html"):
text = p.read_text()
text = text.replace("old", "new")
p.write_text(text)https://stackoverflow.com/questions/69297556
复制相似问题