0

I have a file where I want to replace a string, but all it's doing is appending the end of the file with the replaced string. How can I replace the original occurrences of [NAME] with a string?

Input file

The following are the names of company
 [NAME]
 [NAME]
 [NAME]

Incorporated

When I run my script with a replace I get this.

The following are the names of company
 [NAME]
 [NAME]
 [NAME]

Incorporated
 Julie
 Stan
 Nick

Desired output

The following are the names of company
 Julie
 Stan
 Nick

Incorporated

Python code

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() 
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
GoldenEagle
  • 115
  • 1
  • 2
  • 15
  • Don't you want to read from your input file?? – agold Oct 26 '15 at 14:39
  • Line 8: `TypeError: 'in ' requires string as left operand, not list` ...Do you mean `if '[NAME]' in row:`? – glibdud Oct 26 '15 at 14:40
  • Possible duplicate of [Is it possible to modify lines in a file in-place?](http://stackoverflow.com/questions/5453267/is-it-possible-to-modify-lines-in-a-file-in-place) – glibdud Oct 26 '15 at 15:02

2 Answers2

3

Open the input file, and then write to the input file replacing "[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()
agold
  • 6,140
  • 9
  • 38
  • 54
2

You can use this one-liner:

output.replace("[NAME]", "%s") % tuple(name)

But, amount of names must always be the same as in file.

Sergius
  • 908
  • 8
  • 20
  • What version of Python? I'm getting an `AttributeError`, no attribute called "replace". – glibdud Oct 26 '15 at 14:45
  • 2.6 and 2.7 works the same. output must be string, not just opened file: output=open("output.txt","r+").read() – Sergius Oct 26 '15 at 14:48
  • Ok, thanks for that clarification. So that the asker knows, this just converts the file to a string and performs replacement on the string. He still needs to write the contents of the string back to the file. – glibdud Oct 26 '15 at 14:51