How to search and replace text in a file in Python ?
In this article, we will learn how we can replace text in a file using python.
Method 1: Searching and replacing text without using any external module
Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents:
To replace text in a file we are going to open the file in read-only using the open() function. Then we will t=read and replace the content in the text file using the read() and replace() functions.
Syntax: open(file, mode=’r’)
Parameters:
- file : Location of the file
- mode : Mode in which you want toopen the file.
Then we will open the same file in write mode to write the replaced content.
Python3
search_text = "dummy"
replace_text = "replaced"
with open (r 'SampleFile.txt' , 'r' ) as file :
data = file .read()
data = data.replace(search_text, replace_text)
with open (r 'SampleFile.txt' , 'w' ) as file :
file .write(data)
print ( "Text replaced" )
|
Output:
Text replaced
Method 2: Searching and replacing text using the pathlib2 module
Let see how we can search and replace text using the pathlib2 module. First, we create a Text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents:
Install pathlib2 module using the below command:
pip install pathlib2
This module offers classes representing filesystem paths with semantics appropriate for different operating systems. To replace the text using pathlib2 module we will use the Path method of pathlib2 module.
Syntax: Path(file)
Parameters:
- file: Location of the file you want to open
In the below code we are replacing “dummy” with “replaced” in our text file. using the pathlib2 module.
Code:
Python3
from pathlib2 import Path
def replacetext(search_text, replace_text):
file = Path(r "SampleFile.txt" )
data = file .read_text()
data = data.replace(search_text, replace_text)
file .write_text(data)
return "Text replaced"
search_text = "dummy"
replace_text = "replaced"
print (replacetext(search_text, replace_text))
|
Output:
Text replaced
Method 3: Searching and replacing text using the regex module
Let see how we can search and replace text using the regex module. We are going to use the re.sub( ) method to replace the text.
Syntax: re.sub(pattern, repl, string, count=0, flags=0)
Parameters:
- repl : Text you want to add
- string : Text you want to replace
Code:
Python3
import re
def replacetext(search_text,replace_text):
with open ( 'SampleFile.txt' , 'r+' ) as f:
file = f.read()
file = re.sub(search_text, replace_text, file )
f.seek( 0 )
f.write( file )
f.truncate()
return "Text replaced"
search_text = "dummy"
replace_text = "replaced"
print (replacetext(search_text,replace_text))
|
Output:
Text replaced
Method 4: Using fileinput
Let see how we can search and replace text using the fileinput module. For this, we will use FileInput() method to iterate over the data of the file and replace the text.
Syntax: FileInput(files=None, inplace=False, backup=”, *, mode=’r’)
Parameters:
- files : Location of the text file
- mode : Mode in which you want toopen the file
- inplace : If value is True then the file is moved to a backup file and
- standard output is directed to the input file
- backup : Extension for the backup file
Code:
Python3
from fileinput import FileInput
def replacetext(search_text, replace_text):
with FileInput( "SampleFile.txt" , inplace = True ,
backup = '.bak' ) as f:
for line in f:
print (line.replace(search_text,
replace_text), end = '')
return "Text replaced"
search_text = "dummy"
replace_text = "replaced"
print (replacetext(search_text, replace_text))
|
Output:
Text replaced
Last Updated :
14 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...