Last modified: May 14, 2023 By Alexander Williams
Replace Text in File Using Python [Simple Example]
In this tutorial, we're going to learn how to replace text in a file by following these steps:
1. Open the file on reading and writing r+ mode.
2. Read the file.
3. replace text in the output file.
4. Write the result on the same file.
Let's see the example:
Replacing a Text in a File [Example]
file.txt:
Now, let's replace PHP with PYTHON.
#openfile
with open('file.txt', 'r+') as f:
#read file
file_source = f.read()
#replace 'PHP' with 'PYTHON' in the file
replace_string = file_source.replace('PHP', 'PYTHON')
#save output
f.write(replace_string)
Result:
file.txt:
As you can see, PHP has been replaced with PYTHON