GoldenEagle
GoldenEagle

Reputation: 125

Replace a string in file in it's original place python

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() 

Upvotes: 0

Views: 103

Answers (2)

agold
agold

Reputation: 6276

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()

Upvotes: 3

Sergius
Sergius

Reputation: 986

You can use this one-liner:

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

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

Upvotes: 2

Related Questions