Find and replace in a file with regular expression
Wolfgang Grafen
wolfgang.grafen at marconi.com
Wed Jan 31 03:46:56 EST 2007
Just in case you didn't think about it there is a plain replace method for strings
How to quick-search this method with 'dir'
>>> dir("")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> help("".replace)
Help on built-in function replace:
replace(...)
S.replace (old, new[, maxsplit]) -> string
Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument maxsplit is
given, only the first maxsplit occurrences are replaced.
and now how to apply it:
new_text = open(fileName).read().replace("SOURCE", "REPLACE")
which is the preferred method for a simple task like this.
TOXiC wrote:
> 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):
Now how to solve it with a simple regular expression:
>>> import re
>>> re_replace = re.compile("SOURCE").sub
>>>
>>> txt = " SOURCE SOURCE \n SOURCE "
>>>
>>> print re_replace("REPLACE", txt)
' REPLACE REPLACE \n REPLACE '
>>> new_text = re_replace("REPLACE", open(fileName).read())
A regular expression for this task is kind of overkill. Mastering
regular expression is the efford very worth.
Wolfgang Grafen
More information about the Python-list
mailing list