pythontextfile-handlingcodio

Python - how to replace occurances in text files?


I am working on my school work for 'Intro to Scripting' and I am stuck on how to replace in a text file.

The challenge is asking me to read the contents of the text file, which I did with the code below:

filepath = I

file1 = open(filepath, 'r')
print(file1.read())
file1.close()

Now it's asking me to replace the variable set for 'S' with the variable set for 'T', and I can't for the life of me figure out how to do this.

Edit: This is an online class, so peer collaboration is non-existent, we also use Codio for this work, and nothing I've tried from other questions asked has worked, nor does any of the class reading give examples.


Solution

  • If I am Correct If you want to Just Replace S With T and save output in another file use following code

    f1 = open('data.txt', 'r')
    f2 = open('output.txt', 'w')
    for line in f1:
        f2.write(line.replace('S', 'T'))
    f1.close()
    f2.close()