python - Find a file on a PC and replace a string erases whole file -


i need particular file on pc , replace portion of repeats of string within file. using python 2.6. script finds file instead of replacing instances of string, wipes file blank. idea why?

import os os.path import join import fileinput lookfor = "particular.txt" texttosearch = "alonglineoftext@thefile" texttoreplace = "alonglineoftext@withnewtextinthefile" root, dirs, files in os.walk('c:\\'):   print "searching", root   if lookfor in files:     line in fileinput.fileinput((join(root, lookfor)),inplace=1):         line = line.replace(texttosearch, texttoreplace)         print line     break 

any suggestions?

thanks

i tested code , works fine 1 small bug:

the following line:

line = line.replace(texttosearch, texttoreplace) 

should replaced with:

line = line.strip().replace(texttosearch, texttoreplace) 

otherwise each line appended newline - reason don't find replacements (since you're expecting them in different (original) line-numbers)


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -