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

Kent Johnson kent37 at tds.net
Fri Oct 20 00:25:14 CEST 2006


Danny Yoo wrote:
> 
>>>>> 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()
> ##################################################################

Wow, that seems like overkill when you can just write
f = open('filename.txt')
f.readlines()
f.close()

In CPython (the regular Python that we usually talk about here, 
implemented in C) a file will be closed automatically as soon as there 
are no references to the file because CPython garbage collects objects 
immediately. This behaviour is not guaranteed by the language though and 
it is different in Jython.
> 
> 
> 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
> ############################################

In Python 2.5 you can use with: to do this:

with open('filename.txt') as f:
   f.readlines()

f is guaranteed to be closed when the block exits.

Kent



More information about the Tutor mailing list