Last modified: Jan 10, 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. 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]

file.txt:

Replace Text in File Using Python [Simple 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)



Result:

file.txt:

Replace Text in File Using Python [Simple Example]

as you can see, PHP has been replaced with PYTHON