How can I open a file, Stud.txt, and then replace any occurences of "A" with "Orange"?
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.