search and replace using a file for computer name

I've got to search for the computer name and replace this with another name in python. These are stored in a file seperated by a space.

xerox fj1336
mongodb gocv1344
ec2-hab-223 telephone24

I know this can be done in linux using a simple while loop.

What I've tried is

#input file
fin = open("comp_name.txt", "rt")
#output file to write the result to
fout = open("comp_name.txt", "wt")
#for each line in the input file
for line in fin:
    #read replace the string and write to output file
    fout.write(line.replace('xerox ', 'fj1336'))
#close input and output files
fin.close()
fout.close()

But the output don't really work and if it did it would only replace the one line.


u can try this way:

with open('comp_name.txt', 'r+') as file:
    content = file.readlines()
    for i, line in enumerate(content):
        content[i] = line.replace('xerox', 'fj1336')
    file.seek(0)
    print(str(content))
    file.writelines(content)