deleting a line from a file

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • eMko

    #1

    deleting a line from a file

    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(ut f8):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
  • Steven D'Aprano

    #2
    Re: deleting a line from a file

    On Sat, 29 Mar 2008 04:13:10 -0700, eMko wrote:
    Is there some easy way how to delete a line from a middle of a file in
    Python?
    If the file is small enough to fit into memory (say, up to a few hundred
    megabytes on most modern PCs):


    lines = open('file', 'r').readlines( )
    del line[100]
    open('file', 'w').writelines (lines)


    Quick and easy for the coder, but not the safest way to do it in serious
    production code because there's no error handling there.

    The only safe way to delete a line from a file (at least under common
    operating systems like Windows, Linux and Mac) is to copy the file
    (without the line you wish to delete) to a temporary file, then replace
    the original file with the new version. That's also how to do it for
    files too big to read into memory.



    --
    Steven

    Comment

    • Paul Rubin

      #3
      Re: deleting a line from a file

      Steven D'Aprano <steve@REMOVE-THIS-cybersource.com .auwrites:
      The only safe way to delete a line from a file (at least under common
      operating systems like Windows, Linux and Mac) is to copy the file
      (without the line you wish to delete) to a temporary file, then replace
      the original file with the new version. That's also how to do it for
      files too big to read into memory.
      You could do it "in place" in all those systems afaik, either opening
      the file for both reading and writing, or using something like mmap.
      Basically you'd leave the file unchanged up to line N, then copy lines
      downward starting from line N+1. At the end you'd use ftrunc to
      shrink the file, getting rid of the duplicate last line.

      Comment

      Working...