[Tutor] reg expression substitution questiony
Michael P. Reilly
arcege@shore.net
Fri, 6 Apr 2001 16:58:19 -0400 (EDT)
Scott Ralph Comboni wrote
> I have used perl -p -i -e 's/someName/replaceName/g' <file name>. Is
> there a way to do this type of substitution with the re module?
> I have tried various ways but all I can come up with is this>>
>
> file = open('config.h').read()
> newfile = open('config.h.new','w')
> s = re.sub('8192', '32768', file)
> newfile.write(s)
> newfile.close()
>
> Is there a way I can just read and write to the same file?
> Thanks Scott
There is no nice way to read and write to the same file (Perl doesn't
do it - it moves the original out of the way first). Doing so creates
seeking problems and possible bytes at the end of the file (if the new
data is shorter).
Python's equivalent of Perl's "-n" and "-p" (with -i) options is the
fileinput module:
import fileinput, re, sys
for line in fileinput.input(inplace=1, backup='.bak'):
# or fileinput.input(['config.h'], inplace=1, backup='.bak') for your file
newline = re.sub('8192', '32768', line)
# sys.stdout gets changed to the output file
sys.stdout.write(s)
# files are closed automatically
Good luck,
-Arcege
--
+----------------------------------+-----------------------------------+
| Michael P. (Arcege) Reilly | arcege@speakeasy.net |