Line replace

Sam Pointon free.condiments at
Sun Jan 1 13:18:11 CET 2006

>  I need some help
>  I have a text file which changes dynamically and has
>  200-1800 lines. I need to replace a line , this line
>  can be located via a text marker like :
>  somelines
>  This is the line to be replaced
>  somemorelines
>  My question is how to do this in place without
>  a temporary file , so that the line after
>  the marker is being replaced with mynewlinetext.

You will either have to read the whole file into memory (at 1800 lines,
this shouldn't be too bad) or read piecementally from the input file,
write the processed output to a new file, delete the input file and
rename the new file to the original file (yes, that's using a temporary
file, but it'll be more memory friendly).

The first solution would look something like this:
import sre
input_file = file('/your/path/here')
input_file_content =
pat = sre.compile(r'^#THIS IS MY MARKER\n.*$')
mat =
while mat:
    input_file_content = pat.sub('New text goes here',
    mat =
file('/your/path/here', 'w').write(input_file_content)

The second one might be cleaner to do using a shell script (assuming
you're on a *nix) - awk or sed are perfect for this type of job - but
the python solution will look like this:

import os
input_file = file('/your/path/goes/here')
output_file = file('/tmp/temp_python_file', 'w')
marked = False
for line in input_file:
    if line == '#THIS IS MY MARKER':
        marked = True
    elif marked:
        output_file.write('New line goes here\n')
os.system('rm /your/path/goes/here')
os.system('mv /tmp/temp_python_file /your/path/goes/here')

More information about the Python-list mailing list