Python基础入门 Day80 文件内容批量搜索与替换

120次阅读
没有评论

共计 1760 个字符,预计需要花费 5 分钟才能阅读完成。

在处理大量文本文档时,我们常常需要进行内容的批量修改。例如将旧公司名称替换为新公司名称,将过期的日期改为新的日期。如果一个文件夹中有几十甚至上百个文件,手动修改显然效率低下。Python 可以轻松完成这种批量搜索与替换任务。

  1. 基本思路
  • 遍历指定目录下的所有文件
  • 打开文件并读取内容
  • 使用字符串替换方法 str.replace() 修改内容
  • 将修改后的内容写回文件
  1. 基础代码示例
import os

def batch_replace(folder_path, old_text, new_text, ext_filter=".txt"):
    for root, _, files in os.walk(folder_path):
        for filename in files:
            if filename.endswith(ext_filter):
                file_path = os.path.join(root, filename)
                with open(file_path, "r", encoding="utf-8") as f:
                    content = f.read()
                
                if old_text in content:
                    new_content = content.replace(old_text, new_text)
                    with open(file_path, "w", encoding="utf-8") as f:
                        f.write(new_content)
                    print(f"{filename}: 替换完成 ")
                else:
                    print(f"{filename}: 未找到指定内容 ")
  1. 使用示例
    假设我们有以下三个文件:
report1.txt 内容:Company ABC is the best.
report2.txt 内容:Company ABC provides services.
report3.txt 内容:No mention of company.

运行以下代码:

if __name__ == "__main__":
    folder = "./docs"
    batch_replace(folder, "Company ABC", "Company XYZ")

执行结果:

report1.txt: 替换完成
report2.txt: 替换完成
report3.txt: 未找到指定内容

替换后的文件:

report1.txt 内容:Company XYZ is the best.
report2.txt 内容:Company XYZ provides services.
report3.txt 内容:No mention of company.
  1. 功能扩展
  • 支持多种后缀文件 :不仅是 .txt,还可以是 .md.html 等。
def batch_replace_multi(folder_path, old_text, new_text, extensions=None):
    if extensions is None:
        extensions = [".txt", ".md", ".html"]
    for root, _, files in os.walk(folder_path):
        for filename in files:
            if any(filename.endswith(ext) for ext in extensions):
                file_path = os.path.join(root, filename)
                with open(file_path, "r", encoding="utf-8") as f:
                    content = f.read()
                if old_text in content:
                    new_content = content.replace(old_text, new_text)
                    with open(file_path, "w", encoding="utf-8") as f:
                        f.write(new_content)
                    print(f"{filename}: 替换完成 ")
  • 避免误操作 :先备份文件,再进行替换。
  • 支持正则表达式 :使用 re.sub() 替换复杂模式,如替换所有日期格式。
  1. 总结
    批量搜索与替换是文档管理、代码迁移、文本清理中的常见需求。通过 Python 自动化处理,可以极大提高效率,并降低人工修改出错的风险。

练习与思考:

  1. 修改程序,增加“替换预览”功能,提示用户是否确认替换。
  2. 使用正则替换,将文档中的日期 2024-01-01 批量改为 2025-01-01
  3. 将此功能与前几天学习的文件整理和重命名工具整合,做成一个实用的文件批处理工具。
正文完
 0
评论(没有评论)