Line replace

Mike Meyer mwm at mired.org
Sun Jan 1 17:02:53 CET 2006


DarkBlue <nomail at nixmail.com> writes:
> pseudocode is like this:
>
> get newlinetext from database  # this is ok done with kinterbas
> preferably check if file not in use by other process
> open file and find desired marker
> go to line after marker and replace that one with newlinetext
> close the file
>
> Should be easy, but I am suffering from New Year writer's block..

This is only easy if the old and new data are exactly the same
size. In line oriented files, that's not normally the case.

The standard solution is to overwrite the entire file. Your code goes
like so:

     get lock on file.
     read in file.
     produce new version of file.
     write out file.
     release lock on file.

Of course, this has the problem that if someothing goes wrong during
the write you're going to be up the creek without a paddle - or much
in the way of a canoe. This is why experienced people always use a
temp file, and do things like so:

     get lock on file
     read in file
     produce new version of file in temp file
     rename temp file to real file
     release lock on file

I can't think of a good reason to skip using the temp file once you
have to write out the entire file.

If you can't deal with writing out the entire file, convert the file
from lines of text to something that can be update in place. It's not
clear how much else is going to have to change to deal with this,
though.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list