Replace string within file contents

Joey picture Joey · Nov 8, 2010 · Viewed 209.2k times · Source

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

Answer

Gareth Davidson picture Gareth Davidson · Nov 8, 2010
with open("Stud.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            fout.write(line.replace('A', 'Orange'))