deleting a line from a file

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Mar 29 07:49:11 EDT 2008


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



More information about the Python-list mailing list