How to Search And Replace A Line In A File In Python

In this post, we will learn how to Search and replace a line in a file in Python which we can perform using an in- built function of the file input Module and for which has the property of providing a convenient way to iterate over lines in a file stored in the local location.

Search

Search And Replacement Of A Line In File

For making the search and replacement in the file stored in the local computer we have given an example below to get it executed as per our choice so to earn more and execute the same just follow the example given below.

import fileinput

# Define the file and the line to changing
filename = 'myfile.txt'
old_line = 'Here I am older'
new_line = 'This is new one'

# Iterate over the lines in the file and changing the old line with the new line
for the line in the file input.input( filename, inplace= True):
    if line.strip() == old_line:
        line = new_line + '\n'
    print( line, end='')

Here we simply accessed a file named as myfile.txt where some text or we can say an old line was stored and we simply try to find that line in the file and simply change it with the new line given at the same time. Where we use the lop to check each line to find or find the match where we can find the line that we are finding and once we find the line we simply need to change it with the line given as new or updated.

There are a few things we need to keep in mind before making such changes in the file itself as this modification is done it the file itself and it is an irreversible change we are doing so once we modify we could vote to make it undone so it is advised to he backup for the same before making any change to avoid any future problems that could strick and get affected.

As in .xls files we have been provided with a function as ctrl + f to find the value of a string in a file, here also we can perform the same thing in the file using file reader which we have done above.

 

 

To learn more about  how we can search and replace a line in a file in Python visit: by stack overflow

To learn more about solutions to different problems and tutorials for the concepts we need to know to work on programming along with different ways to solve any generally asked problems: How To Pass-Variables From different Client To A Linux/Ubuntu Server Which Is Running C?.

Leave a Comment

%d bloggers like this: