[英]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.