[Tutor] reg expression substitution question

D-Man dsh8290@rit.edu
Fri, 6 Apr 2001 16:21:28 -0400


On Fri, Apr 06, 2001 at 02:53:46PM -0400, Scott Ralph Comboni wrote:
| 
| 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?

Same as in C :

file = open( 'config.h' , 'r+' )
data = file.read()
data = re.sub( '8192' , '32768' , data )
file.seek( 0 ) # go back to the begining
file.write( data )
file.close()


This, however, will have extra junk at the end of the file if the data
to write to the file is shorter than the existing data.

To solve that I would recommend the following :

file = open( 'config.h' , 'r' ) # open in 'read' mode
data = file.read()
file.close() # we have all the data, let's close the file

data = re.sub( ... )

file = open( 'config.h' , 'w' ) # open it for writing, note that the
                                # file was just truncated to have length 0
file.write( data )
file.close()


Perhaps using different names for the 'before' and 'after' file/data
objects would be better...

HTH,
-D