Editing a file 'In Place'
Simon Foster
simon at uggs.demon.co.uk
Thu Sep 6 17:44:15 EDT 2001
I'm trying to write a simple piece of code to perform some batch edits
on a text file. So far I have:
import re
import sys
sys.stdout = open( sys.argv[2], 'w' )
pdlpat = r'PDL...:'
pdl = re.compile( pdlpat )
f = open( sys.argv[1], 'r' ).read()
flist = list( f )
startpos = 0
pdlnum = 10
while 1:
m = pdl.search( f, startpos )
if not m: break
flist[m.start():m.end()] = list( 'PDL%03d:' % pdlnum )
pdlnum += 10
startpos = m.end() + 1
for i in flist:
sys.stdout.write( i )
Is there any way to avoid turning the inpuit into a list just so that
I can modify it. I would like to just do something like this:
import re
import sys
sys.stdout = open( sys.argv[2], 'w' )
pdlpat = r'PDL...:'
pdl = re.compile( pdlpat )
f = open( sys.argv[1], 'r' ).read()
startpos = 0
pdlnum = 10
while 1:
m = pdl.search( f, startpos )
if not m: break
f[m.start():m.end()] = 'PDL%03d:' % pdlnum )
pdlnum += 10
startpos = m.end() + 1
print f
But of course, strings are immutable, so this does not work. Is there
an idiomatic way of doing this?
--
Simon Foster
Cheltenham
England
More information about the Python-list
mailing list