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
Post a Comment