萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 文件搜索與替換工具類:支持正則、差異顯示、批量處理

功能特性

  • 遞歸遍歷目錄,fnmatch 過濾文件。
  • 支持字符串字面量或正則表達式搜索/替換。
  • 預覽模式(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'))

正則替換(Django URL 標簽遷移)

import re
SearchAndReplace(
    '/project/templates',
    re.compile(r'{%\s*url\s+(.*?)\s*%}'),
    r"{% url '\1' %}",
    file_filters=('*.html',))

總結

該工具類封裝了文件遍歷、編碼處理、正則/字面量替換、差異預覽、安全寫入,適合代碼重構、批量配置修改等場景。

copyright © 萬盛學電腦網 all rights reserved