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

如何用Python基于input.txt改写template.txt,跳过注释行并替换内容

Python实现文本模板替换与文件生成

完整实现代码

# 读取input.txt的内容,提取非空行并去除首尾空白
with open('input.txt', 'r') as input_file:
    input_content = [line.strip() for line in input_file if line.strip()]

# 读取template.txt,过滤注释行(#开头)和空行
with open('template.txt', 'r') as template_file:
    valid_template = [line.strip() for line in template_file if line.strip() and not line.startswith('#')]

# 根据需求示例,模板应仅保留一条有效行,若有多行可调整逻辑
if len(valid_template) != 1:
    raise ValueError("template.txt中需存在且仅存在一条非注释的模板行")

# 执行替换生成结果
output_content = []
for item in input_content:
    output_content.append(valid_template[0].replace('BKUP', item))

# 将结果写入新文件
with open('output.txt', 'w') as output_file:
    output_file.write('\n'.join(output_content))

代码说明

  1. 读取输入文件:提取input.txt中的非空内容,去除每行首尾空白后存入列表,避免空行干扰。
  2. 过滤模板注释:读取template.txt时,直接跳过以#开头的注释行和空行,只保留需要替换的模板内容。
  3. 执行替换逻辑:遍历input.txt的每一行内容,将模板中的BKUP字符串替换为当前行内容,收集所有替换结果。
  4. 保存结果:把最终生成的内容写入output.txt,每行单独存储。

预期输出

运行代码后,output.txt的内容为:

This is ACTUAL.
This is IN USE.
This is NOT TESTING.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:35:28