Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Using python 3, Can anyone tell me how to search and replace text in a file?

Look at my code:

import os

import sys

import fileinput

print ("Text to search for:")

textToSearch = input( "> " )

print ("Text to replace it with:")

textToReplace = input( "> " )

print ("File to perform Search-Replace on:")

fileToSearch  = input( "> " )

#fileToSearch = 'D:\dummy1.txt'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):

    if textToSearch in line :

        print('Match Found')

    else:

        print('Match Not Found!!')

    tempFile.write( line.replace( textToSearch, textToReplace ) )

tempFile.close()

input( '\n\n Press Enter to exit...' )

Input file:

hi this is abcd hi this is abcd

This is dummy text file.

This is how search and replace works abcd

At the point when I search and replace the word 'ram' with 'abcd' in above information document, it functions as an appeal. Yet, when I do it the other way around for example replacing 'abcd' by 'ram', some garbage characters are left toward the end.

Replacing 'abcd' with 'ram'

hi this is ram hi this is ram

This is dummy text file.

This is how search and replace works rambcd

1 Answer

0 votes
by (26.4k points)

Here, fileinput as of now supports inplace editing. It diverts stdout to the file for this situation:

#!/usr/bin/env python3

import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:

    for line in file:

        print(line.replace(text_to_search, replacement_text), end='')

Are you interested to learn the concepts of Python? Join the python training course fast!

Related questions

+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...