how to count lines in a file ?

Richard Jones rjones at ekit-inc.com
Wed Jul 24 20:15:40 EDT 2002


On Thu, 25 Jul 2002 9:56 am, Delaney, Timothy wrote:
> > From: Richard Jones [mailto:rjones at ekit-inc.com]
> >
> > On Thu, 25 Jul 2002 8:31 am, Delaney, Timothy wrote:
> > > > From: Bo M. Maryniuck [mailto:b.maryniuk at forbis.lt]
> > > >
> > > > print len(open('/etc/passwd').readlines())
> >
> > Sorry, I'm coming in to this thread halfway through, but I
> > need to know why
> > that code is broken? Is it the
> > "open('/etc/passwd').readlines()"? That's a
> > very common pattern, as you note, because people think it is
> > perfectly
> > legitemate. What about it is broken? Why isn't it pointed out
> > more often that
> > it _is_ broken?
>
> We had this discussion just recently, but yes, that is precisely what is
> broken.
>
> What is broken? The file is never explicitly closed.

As far as the community is concerned, the file is explicitly closed because no 
reference to it is retained. No, this is not documented. Then again, the 
documentation makes no claims about any sort of behaviour when the object is 
collected. The community has, reasonably enough I think, always assumed (for 
a very long time in many public ways) that the file is closed when it is 
collected! As to Jython not closing the file - well, I'd consider that a 
bug...


> Why is it broken? There are no guarantees that the file will be closed
> either:
>
> 1. Immediately (the assumption in code that uses the above construct);

See my response above.


> It is explicitly documented that yo may not rely on reference-counting
> semantics for such things (Paul Rubin - take note please).

Where? I'm looking at the latest library reference for file objects, and it 
makes no such statement. Unfortunately, it makes no statement either way, and 
there's a lot of art out there that takes advantage of the close-on-collect 
behaviour :(


    Richard





More information about the Python-list mailing list