[英]Run multiple find and replaces in Python (on every file in the folder and sub-folder)
I have a folder (courses) with sub-folders and a random number of files. 我有一个文件夹(课程),包含子文件夹和随机数量的文件。 I want to run multiple search and replaces on those random files.
我想运行多个搜索并替换这些随机文件。 Is it possible to do a wild card search for
.html
and have the replaces run on every html file ? 是否可以对
.html
进行通配符搜索并在每个html文件上运行替换?
Search and replaces: 搜索和替换:
"</b>"
to "</strong>"
"</b>"
到"</strong>"
"</a>"
to "</h>"
"</a>"
到"</h>"
"<p>"
to "</p>"
"<p>"
到"</p>"
Also all these replaces have to be run on every file in the folder and sub-folders. 此外,所有这些替换都必须在文件夹和子文件夹中的每个文件上运行。
Thank you so much 非常感谢
Try this, 尝试这个,
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()
You can change os.walk('./')
to os.walk('/anyFolder/')
你可以将
os.walk('./')
更改为os.walk('/anyFolder/')
使用glob
模块获取*.html
文件列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.