[英]Run multiple find and replaces in Python (on every file in the folder and sub-folder)
我有一个文件夹(课程),包含子文件夹和随机数量的文件。 我想运行多个搜索并替换这些随机文件。 是否可以对.html
进行通配符搜索并在每个html文件上运行替换?
搜索和替换:
"</b>"
到"</strong>"
"</a>"
到"</h>"
"<p>"
到"</p>"
此外,所有这些替换都必须在文件夹和子文件夹中的每个文件上运行。
非常感谢
尝试这个,
import os
from os.path import walk
mydict = {"</b>":"</strong>", "</a>":"</h>", "<p>":"</p>"}
for (path, dirs, files) in os.walk('./'):
for f in files:
if f.endswith('.html'):
filepath = os.path.join(path,f)
s = open(filepath).read()
for k, v in mydict.iteritems():
s = s.replace(k, v)
f = open(filepath, 'w')
f.write(s)
f.close()
你可以将os.walk('./')
更改为os.walk('/anyFolder/')
使用glob
模块获取*.html
文件列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.