如何用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))
代码说明
- 读取输入文件:提取
input.txt中的非空内容,去除每行首尾空白后存入列表,避免空行干扰。 - 过滤模板注释:读取
template.txt时,直接跳过以#开头的注释行和空行,只保留需要替换的模板内容。 - 执行替换逻辑:遍历
input.txt的每一行内容,将模板中的BKUP字符串替换为当前行内容,收集所有替换结果。 - 保存结果:把最终生成的内容写入
output.txt,每行单独存储。
预期输出
运行代码后,output.txt的内容为:
This is ACTUAL.
This is IN USE.
This is NOT TESTING.
内容的提问来源于stack exchange,提问作者Samael2021
相关产品推荐
相关产品推荐

