Search and Replace a Text in a File in Python
In this article, we will learn to search and replace a text of a file in Python. We will use some built-in functions and some custom codes as well. We will replace text, or strings within a file using mentioned ways.
Python provides multiple built-in functions to perform file handling operations. Instead of creating a new modified file, we will search a text from a file and replace it with some other text in the same file. This modifies the file with new data. This will replace all the matching texts within a file and decreases the overhead of changing each word. Let us discuss some of the mentioned ways to search and replace text in a file in Python.
Sample Text File
We will use the below review.text file to modify the contents.
In the movie Ghost
the joke is built on a rock-solid boundation
the movie would still work played perfectly straight
The notion of a ghost-extermination squad taking on
the paramal hordes makes a compelling setup for a big-budget adventure of any stripe
Indeed, the film as it stands frequently allows time to pass without a gag
But then comes the punch line: the characters are funny
And because we’ve been hooked by the story, the humor the characters provide is all the richer.
Example: Use replace() to Replace a Text within a File
The below example uses
replace() function to modify a string within a file. We use the review.txt file to modify the contents. It searches for the string by using for loop and replaces the old string with a new string.
open(file,'r') - It opens the review.txt file for reading the contents of the file.
strip() - While iterating over the contents of the file, strip() function strips the end-line break.
replace(old,new) - It takes an old string and a new string to replace its arguments.
file.close() - After concatenating the new string and adding an end-line break, it closes the file.
open(file,'w') - It opens the file for writing and overwrites the old file content with new content.
reading_file = open("review.txt", "r")
new_file_content = ""
for line in reading_file:
stripped_line = line.strip()
new_line = stripped_line.replace("Ghost", "Ghostbusters")
new_file_content += new_line +"\n"
writing_file = open("review.txt", "w")
Example: Replace a Text using Regex Module
An alternative method to the above-mentioned methods is to use Python’s
regex module. The below example imports regex module. It creates a function and passed a file, an old string, and a new string as arguments. Inside the function, we open the file in both read and write mode and read the contents of the file.
compile() - It is used to compile a regular expression pattern and convert it into a regular expression object which can then be used for matching.
escape() - It is used to escape special characters in a pattern.
sub() - It is used to replace a pattern with a string.
#importing the regex module
#defining the replace method
def replace(filePath, text, subs, flags=0):
with open(file_path, "r+") as file:
#read the file contents
file_contents = file.read()
text_pattern = re.compile(re.escape(text), flags)
file_contents = text_pattern.sub(subs, file_contents)
#calling the replace method
replace(file_path, text, subs)
FileInput in Python
FileInput is a useful feature of Python for performing various file-related operations. For using FileInput,
fileinput module is imported. It is great for throwaway scripts. It is also used to replace the contents within a file. It performs searching, editing, and replacing in a text file. It does not create any new files or overheads.
FileInput(filename, inplace=True, backup='.bak')
backup - The backup is an extension for the backup file created before editing.
Example: Search and Replace a Text using FileInput and replace() Function
The below function replaces a text using
filename = "review.txt"
with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f:
for line in f:
if("paramal" in line):
print(line.replace("paramal","paranormal"), end ='')
print(line, end ='')
In this article, we learned to search and replace a text, or a string in a file by using several built-in functions such as
FileInput module. We used some custom codes as well. We saw outputs too to differentiate between the examples. Therefore, to search and replace a string in Python user can load the entire file and then replaces the contents in the same file instead of creating a new file and then overwrite the file.