How to search and replace text in a file in Python ?

14 Sep, 2021
In this article, we will learn how we can replace text in a file using python.
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
# creating a variable and storing the text# that we want to searchsearch_text = "dummy"  # creating a variable and storing the text# that we want to addreplace_text = "replaced"  # Opening our text file in read only# mode using the open() functionwith open(r'SampleFile.txt', 'r') as file:      # Reading the content of the file    # using the read() function and storing    # them in a new variable    data = file.read()      # Searching and replacing the text    # using the replace() function    data = data.replace(search_text, replace_text)  # Opening our text file in write only# mode to write the replaced contentwith open(r'SampleFile.txt', 'w') as file:      # Writing the replaced data in our    # text file    file.write(data)  # Printing Text replacedprint("Text replaced")
Output:
Text replaced
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
# Importing Path from pathlib2 modulefrom pathlib2 import Path  # Creating a function to# replace the textdef replacetext(search_text, replace_text):      # Opening the file using the Path function    file = Path(r"SampleFile.txt")      # Reading and storing the content of the file in    # a data variable    data = file.read_text()      # Replacing the text using the replace function    data = data.replace(search_text, replace_text)      # Writing the replaced data    # in the text file    file.write_text(data)      # Return "Text replaced" string    return "Text replaced"    # Creating a variable and storing# the text that we want to searchsearch_text = "dummy"  # Creating a variable and storing# the text that we want to updatereplace_text = "replaced"  # Calling the replacetext function# and printing the returned statementprint(replacetext(search_text, replace_text))
Output:
Text replaced
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
# Importing re moduleimport re  # Creating a function to# replace the textdef replacetext(search_text,replace_text):      # Opening the file in read and write mode    with open('SampleFile.txt','r+') as f:          # Reading the file data and store        # it in a file variable        file = f.read()                  # Replacing the pattern with the string        # in the file data        file = re.sub(search_text, replace_text, file)          # Setting the position to the top        # of the page to insert data        f.seek(0)                  # Writing replaced data in the file        f.write(file)          # Truncating the file size        f.truncate()      # Return "Text replaced" string    return "Text replaced"  # Creating a variable and storing# the text that we want to searchsearch_text = "dummy"  #Creating a variable and storing# the text that we want to updatereplace_text = "replaced"  # Calling the replacetext function# and printing the returned statementprint(replacetext(search_text,replace_text))
Output:
Text replaced
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
# Importing FileInput from fileinput modulefrom fileinput import FileInput  # Creating a function to# replace the textdef replacetext(search_text, replace_text):      # Opening file using FileInput    with FileInput("SampleFile.txt", inplace=True,                   backup='.bak') as f:          # Iterating over every and changing        # the search_text with replace_text        # using the replace function        for line in f:            print(line.replace(search_text,                               replace_text), end='')      # Return "Text replaced" string    return "Text replaced"    # Creating a variable and storing# the text that we want to searchsearch_text = "dummy"  # Creating a variable and storing# the text that we want to updatereplace_text = "replaced"  # Calling the replacetext function# and printing the returned statementprint(replacetext(search_text, replace_text))
Output:
Text replaced
Picked
Python file-handling-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.