Line replace

Sam Pointon free.condiments at gmail.com
Sun Jan 1 07:18:11 EST 2006


>Hello
>
>  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 MY MARKER
>  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.
>
>Thanks
>Nx

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:
#Untested
import sre
input_file = file('/your/path/here')
input_file_content = input_file.read()
input_file.close()
pat = sre.compile(r'^#THIS IS MY MARKER\n.*$')
mat = pat.search(input_file_content)
while mat:
    input_file_content = pat.sub('New text goes here',
input_file_content)
    mat = pat.search(input_file_content)
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:

#Untested
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')
    else:
        output_file.write(line)
input_file.close()
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