Replace Text in File Using Python [Simple Example]
- Last modified: 22 November 2020
- Category: python tutorial
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]
In the following example, we'll replace a text in file.txt file and write the result in the same file.
file.txt:
![Replace Text in File Using Python [Simple Example] Replace Text in File Using Python [Simple Example]](/theme/img/images.jpeg)
now, we'll 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] Replace Text in File Using Python [Simple Example]](/theme/img/images.jpeg)
as you can see, PHP has been replaced with PYTHON
English today is not an art to be mastered it's just a tool to use to get a result