Find and replace in a file with regular expression

TOXiC GatlingGun at gmail.com
Tue Jan 30 14:52:24 EST 2007


Hi everyone,
First I say that I serched and tryed everything but I cannot figure 
out how I can do it.
I want to open a a file (not necessary a txt) and find and replace a 
string.
I can do it with:

import fileinput, string, sys
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(text.replace(sourceText, replaceText))
    file.close() #Closes the file (write session)
    print "All went well, the modifications are done"

replacemachine(fileQuery, sourceText, replaceText)

Now all went ok but I'm wondering if it's possible to replace text if /
sourceText/ match a regex.
Help me please!
Thx in advance




More information about the Python-list mailing list