使用Python替换文本文件中含指定字符串的行(自定义替换内容)
Python 文本行替换脚本实现
需求说明
处理
Old.txt文件:
- 若某行包含字符串
REL,整行替换为Released- 其余行按如下映射规则匹配替换(匹配到对应关键词则替换为目标值):
- INSP → Submitted
- No Baseline → Draft
- Rev → Reviewed
- APPR → Approved
- DRAFT → Draft
脚本实现
# 定义替换规则,REL优先级最高 replace_rules = [ ("REL", "Released"), ("INSP", "Submitted"), ("No Baseline", "Draft"), ("Rev", "Reviewed"), ("APPR", "Approved"), ("DRAFT", "Draft") ] # 原文件与输出文件路径 input_file = "Old.txt" output_file = "New.txt" # 逐行处理文件 with open(input_file, 'r', encoding='utf-8') as f_in, open(output_file, 'w', encoding='utf-8') as f_out: for line in f_in: line_content = line.strip() is_replaced = False # 遍历规则匹配替换 for keyword, target in replace_rules: if keyword in line_content: f_out.write(target + '\n') is_replaced = True break # 无匹配规则则保留原行 if not is_replaced: f_out.write(line) print(f"处理完成,结果已保存至 {output_file}")
关键说明
- 规则列表按优先级排序,
REL放在最前确保优先匹配 - 使用UTF-8编码读写,避免中文或特殊字符乱码
- 不修改原文件,结果写入新文件,降低数据丢失风险
- 若需直接覆盖原文件,可将
output_file改为input_file(操作前建议备份原文件)
内容的提问来源于stack exchange,提问作者HEMANTH KUMAR MOTUKURI
相关产品推荐
相关产品推荐

