Replace string within file contents


Question

How can I open a file, Stud.txt, and then replace any occurences of "A" with "Orange"?

1
81
11/8/2010 9:22:44 PM

You need to open the input file (reading mode) and write to an output file (writing mode). While writing to the output file use the replace function. Afterwards, rename the file to keep the file name like so:

import os    

file_in = "Stud.txt"
file_out = "tmp.txt"
with open(file_in, "rt") as fin:
    with open(file_out, "wt") as fout:
        for line in fin:
            fout.write(line.replace('A', 'Orange'))

os.rename(file_out, file_in)

In case you want to keep the file name simply write to a temporary file and overwrite the original file afterwards. If it should be a separate file just leave out the os.rename command and you should be fine.

161
7/19/2019 8:32:36 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon