Python替换文件指定行字符串时如何去除首尾多余引号
问题原因
- 你的占位符
$$Replace Here$$在file2.tf中本身被一对双引号包裹,原替换逻辑只替换了占位符内容,外层引号被保留,导致替换后内容首尾多了多余引号。 - 原代码存在两个错误:读取的目标文件名错写为
file2.txt(实际是file2.tf),使用了未定义的变量rep_string。
修复代码
# 读取file1内容,strip可去除末尾多余换行符 with open('file1.txt', 'r', encoding='utf-8') as fd: file1_text = fd.read().strip() # 读取待替换的file2.tf文件 with open('file2.tf', 'r', encoding='utf-8') as fw: file2_text = fw.read() # 连同占位符外层的双引号一起替换 modified_content = file2_text.replace('"$$Replace Here$$"', file1_text) # 写入结果文件 with open('file3.tf', 'w', encoding='utf-8') as fz: fz.write(modified_content)
修复逻辑说明
替换时将占位符和外层的双引号作为整体匹配项,替换后原有的外层引号会被直接删除,仅保留file1内容中本身带的内部引号,完全匹配预期输出格式。
内容的提问来源于stack exchange,提问作者bluebud
相关产品推荐
相关产品推荐

