You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python文本过滤程序自动检索本地文件无需手动拖拽

文本过滤程序优化方案

你当前的代码硬编码了固定文件名first file.txt,只能读取同目录下的同名文件,因此需要手动替换文件才能生效。以下是两种可实现无需手动拖拽指定文件的修改方案:

方案1:自动扫描指定目录下的所有文本文件

无需手动指定文件,程序启动后自动遍历目标目录下所有符合规则的txt文件完成处理,支持全盘扫描:

import os

# 可自定义配置参数
SCAN_DIR = "./"  # 扫描路径,Windows全盘扫描可改为 ["C:/", "D:/"] 后循环遍历,Mac/Linux全盘设为 "/"
TARGET_SUFFIX = ".txt"  # 仅处理txt格式文件
REPLACE_RULES = {"Bob": "James", "Xavier": "Jake"}  # 替换规则,可自行增删
OUTPUT_SUFFIX = "_revised"  # 输出文件命名后缀,避免覆盖原文件

def process_single_file(file_path):
    file_dir, full_name = os.path.split(file_path)
    name, ext = os.path.splitext(full_name)
    output_path = os.path.join(file_dir, f"{name}{OUTPUT_SUFFIX}{ext}")
    with open(file_path, "rt", encoding="utf-8") as in_f, open(output_path, "wt", encoding="utf-8") as out_f:
        for line in in_f:
            for old, new in REPLACE_RULES.items():
                line = line.replace(old, new)
            out_f.write(line)

if __name__ == "__main__":
    for root, _, files in os.walk(SCAN_DIR):
        for file in files:
            if file.lower().endswith(TARGET_SUFFIX) and OUTPUT_SUFFIX not in file:
                process_single_file(os.path.join(root, file))
    print("全部文件处理完成")

注意:全盘扫描耗时较长,建议优先指定常用的文件存放目录提升运行效率。

方案2:支持文件拖拽运行

不需要提前把文件放到指定位置,直接选中任意数量的txt文件拖拽到程序图标(py文件或打包后的exe文件)上,即可自动批量处理:

import sys

REPLACE_RULES = {"Bob": "James", "Xavier": "Jake"}

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("请将待处理的txt文件拖拽到程序图标上运行")
        sys.exit()
    for file_path in sys.argv[1:]:
        if not file_path.lower().endswith(".txt"):
            continue
        output_path = file_path.rsplit(".", 1)[0] + "_revised.txt"
        with open(file_path, "rt", encoding="utf-8") as in_f, open(output_path, "wt", encoding="utf-8") as out_f:
            for line in in_f:
                for old, new in REPLACE_RULES.items():
                    line = line.replace(old, new)
                out_f.write(line)
        print(f"{file_path} 处理完成")

内容的提问来源于stack exchange,提问作者Beginner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:24:03