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


how search , replace text in file using python 3?

here code:

import os import sys import fileinput  print ("text search for:") texttosearch = input( "> " )   print ("text replace with:") texttoreplace = input( "> " )  print ("file perform search-replace on:") filetosearch  = input( "> " ) #filetosearch = 'd:\dummy1.txt'  tempfile = open( filetosearch, 'r+' )  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 exit...' ) 

input file:

hi abcd hi abcd

this dummy text file.

this how search , replace works abcd

when search , replace 'ram' 'abcd' in above input file, works charm. when vice-verse i.e. 'abcd' 'ram', junk characters left @ end.

replacing 'abcd' 'ram'

hi ram hi ram

this dummy text file.

this how search , replace works ram

fileinput supports inplace editing. redirects stdout file in case:

#!/usr/bin/env python3 import fileinput  fileinput.fileinput(filetosearch, inplace=true, backup='.bak') file:     line in file:         print(line.replace(texttosearch, texttoreplace), end='') 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -