deleting a line from a file

Paddy paddy3118 at
Sat Mar 29 19:01:40 CET 2008

On Mar 29, 11:13 am, eMko <mm007.e... at> wrote:
> Hello,
> In Perl, using a Tie::File module I can easily and comfortably delete
> a line from the middle of a text file:
>   my @file;
>   open(DATA, "+<:encoding(utf8):raw" , "file.txt") or return 0;
>   tie @file, 'Tie::File', \*DATA or return 0;
>   splice(@file, $_[0], 1);
>   untie @file;
>   close DATA;
> (when the first argument of the function ($_[0]) is a number of the
> line which should be deleted)
> Is there some easy way how to delete a line from a middle of a file in
> Python?
> Thanks a lot
> eMko

Module fileinput has\;

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 makes it possible to write a filter that
rewrites its input file in place. If the keyword argument
backup='.<some extension>' is also given, it specifies the extension
for the backup file, and the backup file remains around; by default,
the extension is '.bak' and it is deleted when the output file is
closed. In-place filtering is disabled when standard input is read.

- Paddy.

More information about the Python-list mailing list