In this tutorial, we're going to learn how to replace text in a file by following these steps:
1. opening the file on reading and writing r+ mode.
2. reading the file.
3. replace text in the output file.
4. writing the result on the same file.
let's see the example:
Replacing a Text in a File [Example]
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)
as you can see, PHP has been replaced with PYTHON