By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,986 Members | 1,551 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,986 IT Pros & Developers. It's quick & easy.

deleting a line from a file

P: n/a
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
Mar 29 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Mar 29 '08 #2

P: n/a
Steven D'Aprano <st***@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.
Mar 29 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.