Find and replace in a file with regular expression
Matimus
mccredie at gmail.com
Tue Jan 30 15:12:18 EST 2007
The re module is used for regular expressions. Something like this
should work (untested):
import fileinput, string, sys, re
fileQuery = "Text.txt"
sourceText = '''SOURCE'''
replaceText = '''REPLACE'''
def replace(fileName, sourceText, replaceText):
file = open(fileName, "r")
text = file.read() #Reads the file and assigns the value to a
variable
file.close() #Closes the file (read session)
file = open(fileName, "w")
file.write(re.sub(sourceText, replaceText,text))
file.close() #Closes the file (write session)
print "All went well, the modifications are done"
replacemachine(fileQuery, sourceText, replaceText)
More information about the Python-list
mailing list