我有一个文件,我想要替换一个字符串,但它所做的就是用替换的字符串追加文件的末尾。如何用字符串替换[NAME]的原始出现次数?
输入文件
The following are the names of company
[NAME]
[NAME]
[NAME]
Incorporated
当我用替换运行我的脚本时,我得到了这个。
The following are the names of company
[NAME]
[NAME]
[NAME]
Incorporated
Julie
Stan
Nick
期望的输出
The following are the names of company
Julie
Stan
Nick
Incorporated
Python代码
output=open("output.txt","r+")
output.seek(0)
name=['Julie', 'Stan', 'Nick']
i=0
for row in output:
if name in row:
output.write(row.replace('[NAME]',name[i]))
i=i+1
print(row)
for row in output:
print(row)
output.close()
答案 0 :(得分:3)
打开输入文件,然后写入输入文件替换" [NAME]":
input = open("input.txt")
output = open("output.txt","w")
name=['Julie', 'Stan', 'Nick']
i = 0
for row in input:
if "[NAME]" in row:
row=row.replace("[NAME]",name[i])
i+=1
output.write(row)
input.close()
output.close()
答案 1 :(得分:2)
你可以使用这个单行:
output.replace("[NAME]", "%s") % tuple(name)
但是,名称的数量必须始终与文件中的相同。