deleting a line from a file

Paul Rubin http
Sat Mar 29 08:01:57 EDT 2008


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
> 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.



More information about the Python-list mailing list