[Tutor] Trying to extract the last line of a text file

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Oct 19 23:35:18 CEST 2006


>> >> file('filename.txt').readlines()[-1]
>> 
>> > Not to hijack the thread, but what stops you from just putting a 
>> > file.close() after your example line?
>> 
>> Which file should file.close() close?  The problem is that we don't 
>> have a handle on the particular file we want to close off.
>>
> Oh wow.. I totally missed that... nevermind.. ignore that question =D


Hi Chris,

No, no, it's an interesting one.  It turns out that there IS a way to 
sorta do what you're thinking:

############################################################
class FilePool:
     """A small demo class to show how we might keep track of
     files opened with us."""
     def __init__(self):
         self.pool = []

     def open(self, filename):
         f = open(filename)
         self.pool.append(f)
         return f

     def closeAll(self):
         for f in self.pool:
             f.close()
         self.pool = []
fp = FilePool()
############################################################


Once we have FilePool, we might say something like:

##################################################################
print "the last line is:", fp.open('filename.txt').readlines()[-1]
fp.closeAll()
##################################################################


This is similar in spirit to the idea of "autorelease" memory pools used 
by the Objective C language.  We use some resource "manager" that does 
keep a handle on resources.  That manager then has the power and 
responsiblity to call close() at some point.  So one might imagine doing 
something like:

############################################
create a manager
try:
     ... # use resources that the manager doles out
finally:
     use the manager to close everything down
############################################


So your question may have seemed like a dumb one, but it's actually a good 
one.  *grin*


Good luck!


More information about the Tutor mailing list