search_only=True)顯示統一差異格式。.svn 等版本控制目錄。import os, re, time, fnmatch, difflib
class SearchAndReplace:
def __init__(self, search_path, search_str, replace_str,
search_only=True, file_filters=('*.*',)):
self.path = search_path
self.search_str = search_str
self.replace_str = replace_str
self.search_only = search_only
self.filters = file_filters
self.is_re = isinstance(search_str, type(re.compile('')))
self._run()
def _run(self):
print(f"Search '{self.search_str}' in [{self.path}]...")
t0 = time.time()
cnt = self._walk()
print(f"{cnt} files searched in {time.time()-t0:.2f} sec.")
def _walk(self):
cnt = 0
for root, dirs, files in os.walk(self.path):
if '.svn' in root: continue
for f in files:
if any(fnmatch.fnmatch(f, pat) for pat in self.filters):
self._process(os.path.join(root, f))
cnt += 1
return cnt
def _process(self, filepath):
with open(filepath, 'r') as f: old = f.read()
if self.is_re or self.search_str in old:
new = self._replace(old)
if new == old: return
print(filepath)
self._show_diff(old, new)
if not self.search_only:
with open(filepath, 'w') as f: f.write(new)
print(" -> Written")
def _replace(self, content):
if self.is_re:
return self.search_str.sub(self.replace_str, content)
return content.replace(self.search_str, self.replace_str)
def _show_diff(self, old, new):
for line in difflib.unified_diff(
old.splitlines(), new.splitlines(),
fromfile='old', tofile='new', lineterm=''):
print(f" {line}")
SearchAndReplace(
'/project/src', 'old_api', 'new_api',
search_only=False, file_filters=('*.py', '*.js'))
import re
SearchAndReplace(
'/project/templates',
re.compile(r'{%\s*url\s+(.*?)\s*%}'),
r"{% url '\1' %}",
file_filters=('*.html',))
該工具類封裝了文件遍歷、編碼處理、正則/字面量替換、差異預覽、安全寫入,適合代碼重構、批量配置修改等場景。