[Tutor] How to delete the last line from a file efficiently?

Rohit Kumar krohit at mail.zeomega.com
Thu Feb 18 11:05:36 CET 2010

Here is the efficient code than your code: 
lines = file('file1.txt', 'r').readlines() 
print lines 
del lines[-1] 
print lines 
file('file1.txt', 'w').writelines(lines) 

Please let me know if any issues. 
Rohit Kumar 
Software Developer - Trainee 
ZeOmega Infotech Private Limited 
RLP Building, Bangalore - 560047 
Phone: 080-41666070 Ext: 126 
krohit at zeomega.com 
Proven. Progressive. Partner. 


This message (including any attachments) may contain ZeOmega's 
confidential information, protected by law. Forwarding it to 
individuals, other than those with a need to know, without the 
permission of the sender, is prohibited. This message is intended for 
specific individual(s) or entity to whom it is intended even if 
addressed incorrectly. If you are not the intended recipient, you 
should delete this message and are hereby notified that any 
disclosure,copying, or distribution of this message or taking any 
action based upon it, is strictly prohibited. 

----- Original Message ----- 
From: "Joson" <zhuchunml at gmail.com> 
To: Tutor at python.org 
Sent: Thursday, February 18, 2010 3:00:48 PM 
Subject: [Tutor] How to delete the last line from a file efficiently? 

Hi all, 
Now I have a text file about 1MB. Sometimes I need to remove the last line. 
The current method I use is reading all content, finding the last sentence, remove it and write the new content to the file. 
So, it need to read a 1MB file and write a 1MB file. It's ineffictient, I think. Are there any other methods? 

Tutor maillist - Tutor at python.org 
To unsubscribe or change subscription options: 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100218/e681206f/attachment.htm>

More information about the Tutor mailing list