Hi, what I'd like to do is edit an input file for a calculation with
Python. Let's say that I have an input file like the following
------------------------------>>
BLAH BLAH BLAH
Other inputs, Volume 940 m^3, maybe some more stuff
STUFF STUFF
------------------------------>>
So let's say I want to edit this file and change Volume from 940 to 950.
This is how I would guess I would do something like it:
---------------------------------------------
import re
expr=r'.*Volume\s+(?P<VolValue>\d+[.]?[\d+]?)'
exprComp=re.compile(expr)
infile=open('myfile','r')
outfile=open('outfile','w')
for line in infile:
match=exprComp.search(line)
if match:
newline=<HELP ME!>
print >> outfile, newline
else:
print >> outfile, line
infile.close()
outfile.close()
------------------------------
So what I would like to do in the section labeled <HELP ME!> is to use
something like the re.sub() function and replace the contents of the
"VolValue" group with another number. However I am not sure how exactly
to do this. I feel like I could use the information that's on this
website:http://www.regular-expressions.info/python.html to do it but it
seems that I can only USE captured groups, not REPLACE them. This makes
it seem to me that I would need my groups to be everything that I WASN'T
going to replace. Then I could do something like this:
re.sub(regex,\g<StuffBeforeVolumeValue>950\g<StuffAfterVolumeValue>)
or something along those lines. Although that is really so much uglier
than if i could simply replace the captured group.
Please help pythonistas :)
--
http://mail.python.org/mailman/listinfo/python-list