Signup/Sign In
PUBLISHED ON: FEBRUARY 23, 2021

Search and Replace a Line in a File in Python

In this article, we will learn to search and replace the contents of a file in Python. We will use some built-in functions and some custom codes as well. We will replace lines 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 line from a file and replace it with some other line in the same file. This modifies the file with new lines of data. This will replace all the matching lines within a file and decreases the overhead of changing each line. Let us discuss some of the mentioned ways to search and replace lines 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.

FileInput in Python

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.

Syntax

FileInput(filename, inplace=True, backup='.bak')

Parameters

backup - The backup is an extension for the backup file created before editing.

Example: Replace only the First Line of a File using FileInput

The below example takes the review.txt file and changes its first line with the new line.

import fileinput

filename = "review.txt"

with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f:
    for line in f:
        if(f.isfirstline()):
            print("In the case of Ghostbusters", end ='\n')
        else:
            print(line, end='') 

Output:

Example: Search any Line of a File and Replace it using FileInput

The below example takes the review.txt file and changes a particular line with the new line within the file. It searches for the line and replaces it.

import fileinput

filename = "review.txt"

with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f:
    for line in f:
        if("the movie would still work played perfectly straight\n" == line):
            print("the movie work played perfectly straight",end ='\n')
        else:
            print(line, end ='') 

Output:

Conclusion

In this article, we learned to search and replace a line in a file by using several built-in functions such as replace(), and FileInput module. We used some custom code as well. We saw outputs too to differentiate between the examples. Therefore, to search and replace a line in Python user can load the entire file and then replace the contents in the same file instead of creating a new file and then overwrite the file.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.