需要帮助运行for循环来替换txt文件中的一行,并将其保存为python中的新文件



我想编辑一个特定的。txt文件,其中在一行中包含一个字符串,我想用另一个字符串名称替换,并将它们保存在一个新的。txt文件中。到目前为止,我已经完成了以下代码,代码只保存了最后一个输出6的新编辑的.txt文件,而不是从1到6的所有输出。从1-5中输出的.txt文件没有文本。任何想法在哪里的问题是,我如何能修复我的代码,使其按预期工作?提前谢谢你。

input = open("C:Users...file.txt", "rt")
for n in range(1,7):
for line in input:
output= open("file" + str(n) + "new.txt", "wt")
output.write(line.replace("data_sample.csv", "data_"+ str(n) +"_new.csv"))
我同意Adham的评论。我还建议将读取输入文件移到最外层的for循环中。下面的代码片段应该按照预期创建这些文件
for n in range(1,7):
input = open("C:Users...file.txt", "rt")
output= open("file" + str(n) + "new.txt", "wt")
for line in input:
output.write(line.replace("data_sample.csv", "data_"+ str(n) +"_new.csv"))
output.close()

最新更新