如何用Python批量替换多文件指定位置字符并实现自动化?
批量处理.nc1文件的条件替换方案
核心功能实现脚本
以下Python脚本实现批量处理指定目录下的所有.nc1文件,按规则替换第二列后的"u"字符,并保留原目录结构保存到输出目录:
import os import re def process_file(input_path, output_path): """处理单个.nc1文件的替换逻辑""" with open(input_path, 'r', encoding='utf-8') as f_in: lines = f_in.readlines() processed_lines = [] for line in lines: stripped_line = line.rstrip('\n') # 判断行首匹配规则 if stripped_line.startswith((' o', ' u')): # 替换第二列数值后的u为s processed_line = re.sub(r'(^ [ou]\s+\d+)u', r'\1s', stripped_line) else: # 其他行替换第二列数值后的u为o processed_line = re.sub(r'(^.*?\s+\d+)u', r'\1o', stripped_line) processed_lines.append(processed_line + '\n') # 确保输出目录存在 os.makedirs(os.path.dirname(output_path), exist_ok=True) with open(output_path, 'w', encoding='utf-8') as f_out: f_out.writelines(processed_lines) def batch_process(input_dir, output_dir): """批量遍历目录下所有.nc1文件""" for root, _, files in os.walk(input_dir): for file in files: if file.endswith('.nc1'): input_path = os.path.join(root, file) # 保留原目录结构到输出目录 relative_path = os.path.relpath(input_path, input_dir) output_path = os.path.join(output_dir, relative_path) process_file(input_path, output_path) print(f"处理完成:{input_path} -> {output_path}") # 配置输入输出目录,根据实际路径修改 INPUT_DIR = r'C:\你的输入文件夹路径' OUTPUT_DIR = r'C:\你的输出文件夹路径' if __name__ == '__main__': # 支持两种运行方式:直接运行批量处理目录,或拖放文件到脚本上处理单个/多个文件 import sys if len(sys.argv) > 1: # 处理拖放的文件,输出到固定目录 for file_path in sys.argv[1:]: if file_path.endswith('.nc1'): file_name = os.path.basename(file_path) output_path = os.path.join(OUTPUT_DIR, file_name) process_file(file_path, output_path) print(f"处理完成:{file_path} -> {output_path}") else: # 批量处理指定目录 batch_process(INPUT_DIR, OUTPUT_DIR)
自动拖放实时处理方案
如果需要实现拖放文件到指定文件夹时自动执行处理,可以用watchdog库监听文件夹变化:
步骤1:安装依赖
pip install watchdog
步骤2:监听脚本
import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import os import re # 复用核心处理函数 def process_file(input_path, output_path): with open(input_path, 'r', encoding='utf-8') as f_in: lines = f_in.readlines() processed_lines = [] for line in lines: stripped_line = line.rstrip('\n') if stripped_line.startswith((' o', ' u')): processed_line = re.sub(r'(^ [ou]\s+\d+)u', r'\1s', stripped_line) else: processed_line = re.sub(r'(^.*?\s+\d+)u', r'\1o', stripped_line) processed_lines.append(processed_line + '\n') os.makedirs(os.path.dirname(output_path), exist_ok=True) with open(output_path, 'w', encoding='utf-8') as f_out: f_out.writelines(processed_lines) class NC1FileHandler(FileSystemEventHandler): def __init__(self, output_dir): self.output_dir = output_dir def on_created(self, event): # 仅处理.nc1文件,跳过目录 if not event.is_directory and event.src_path.endswith('.nc1'): # 等待文件完全写入,避免读取不完整 time.sleep(1) input_path = event.src_path file_name = os.path.basename(input_path) output_path = os.path.join(self.output_dir, file_name) process_file(input_path, output_path) print(f"自动处理完成:{input_path} -> {output_path}") if __name__ == '__main__': # 配置监听目录和输出目录 WATCH_DIR = r'C:\拖放文件的目标文件夹' OUTPUT_DIR = r'C:\处理后的输出文件夹' event_handler = NC1FileHandler(OUTPUT_DIR) observer = Observer() observer.schedule(event_handler, WATCH_DIR, recursive=False) observer.start() print(f"已启动监听:拖入.nc1文件到 {WATCH_DIR} 会自动处理") try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
使用说明
- 运行监听脚本后,保持命令行窗口打开
- 直接将.nc1文件拖放到配置的
WATCH_DIR文件夹中,脚本会自动处理并保存到输出目录
注意事项
- 如果你的.nc1文件编码不是UTF-8,需要修改
open函数中的encoding参数(比如gbk) - 正则表达式可根据实际文件格式调整:如果第二列不是纯数字,可将
\d+替换为\S+匹配任意非空白字符
内容的提问来源于stack exchange,提问作者PythonMaster64
相关产品推荐
相关产品推荐

