Python文件替换与拼接异常:仅生成单份输出的解决求助
问题解决:批量替换并生成多份拼接内容
我有四个文件:file1.txt、file2.txt、file3.txt、file4.txt,还有一个list.txt文件,里面是不同字符串。我想替换file3.txt里的字符串"xxxxxxxx",尝试用Python拼接所有文件内容并替换后生成output.txt,但只得到一份拼接结果。
现有代码
import re info1 = info2 = info3 = info4 = "" # Reading information from the first file with open('file1.txt') as file: info1 = file.read() # Reading information from the second file with open('file2.txt') as file: info2 = file.read() # Reading information from the third file with open('file3.txt') as file: info3 = file.read() #Reading information from the list file with open ('mylist.txt') as file: mylist = file.readlines() for string in mylist: info3 = re.sub("xxxxxxxxxx", string, info3) with open('file4.txt') as file: info4 = file.read() info1 += info2 info2 += info3 info3 += info4 with open ('output.txt', 'w') as file: file.write(info1) file.write(info3)
示例输入
file1.txt内容:Hello Worldfile2.txt内容:My name is Darth Vaderfile3.txt内容:I have come to invade xxxxxxxxxxfile4.txt内容:If you only knew the power of dark side.list.txt内容:tatooine coruscant hoth bespin
当前输出
Hello World My name is Darth Vader I have come to invade tatooine If you only knew the power of dark side.
期望输出(file1.txt内容仅出现一次)
Hello World My name is Darth Vader I have come to invade tatooine If you only knew the power of dark side. My name is Darth Vader I have come to invade coruscant If you only knew the power of dark side. My name is Darth Vader I have come to invade hoth If you only knew the power of dark side. My name is Darth Vader I have come to invade bespin If you only knew the power of dark side.
问题原因与解决方案
问题出在循环逻辑和内容处理顺序上:
- 循环里直接修改
info3,每次替换会覆盖之前的结果,最后只保留了最后一次替换的内容 - 拼接和写入操作都在循环外,所以只生成了一份结果
修改后的代码如下:
import re # 读取所有固定内容 with open('file1.txt') as file: info1 = file.read() with open('file2.txt') as file: info2 = file.read() # 保存file3的原始模板,每次循环都基于模板替换,避免覆盖 with open('file3.txt') as file: info3_template = file.read() with open('file4.txt') as file: info4 = file.read() with open('mylist.txt') as file: mylist = file.readlines() # 处理输出文件 with open('output.txt', 'w') as output_file: # 先写入file1的内容,仅一次 output_file.write(info1) # 遍历每个字符串,生成对应块并写入 for string in mylist: # 去除字符串末尾多余的换行符 string = string.strip() # 用当前字符串替换模板中的占位符 info3 = re.sub("xxxxxxxxxx", string, info3_template) # 拼接并写入file2+替换后的file3+file4 output_file.write(info2) output_file.write(info3) output_file.write(info4) # 可选:添加换行分隔不同块 output_file.write('\n')
关键修改点
- 单独保存
file3.txt的原始模板,每次循环都基于模板重新替换,避免之前的替换结果被覆盖 - 将写入操作放到循环内部,每个字符串对应一次拼接写入
- 用
strip()处理list.txt中的字符串,避免多余换行导致格式混乱
内容的提问来源于stack exchange,提问作者DaSnipeKid
相关产品推荐
相关产品推荐

