deleting a line from a file

Mark Wooding mdw at distorted.org.uk
Tue Apr 1 13:32:41 EDT 2008


Paddy <paddy3118 at googlemail.com> wrote:

> Why not use the fileinput modules functionality to iterate over a file
> in-place,printing just those lines you want?

>From the Python 2.5 manual:

: *Optional in-place filtering:* if the keyword argument `INPLACE=1' is
: passed to `input()' or to the `FileInput' constructor, the file is
: moved to a backup file and standard output is directed to the input
: file (if a file of the same name as the backup file already exists, it
: will be replaced silently).

This behaviour is very dangerous.  If the script fails half-way through,
it will leave the partially-written file in place, with the `official'
name.  The change-over is not atomic, breaking other programs attempting
to read simultaneously with an update.

Two almost-simultaneous updates will corrupt the file without a usable
backup.  The first will back up the input file, and start writing.  A
second will /replace/ the backup file with the partially-constructed
output of the first, and then start processing it; but since its input
is incomplete, it will produce incomplete output.

The safely_writing context manager has none of these defects.

-- [mdw]



More information about the Python-list mailing list