readlines() question

Doug Stanfield DOUGS at oceanic.com
Fri Jun 9 15:43:51 EDT 2000


> [About...]
> > >contents = open('file').readlines()
> > >
> > >is 'file' closed after readlines() finishes? If not, is it 
> possible to
> > >somehow get either the file descriptor or the file object 
> of the opened
> > >file? Thanks,
> 
> [Aahz] 
> > Yes, it's closed.  The anonymous object created by open() gets
> > deallocated after the assignment; part of the cleanup is to silently
> > call close().
> 
[Moshe]
> While what Aahz said can't be said to be untrue, it's hard to call it
> true, either. That is what happens in the *current* *CPython*
> implementation. In no way does the language require it, and 
> specifically,
> for JPython, it is not true.

An answer to the second part of your question which implies you want to
explicitly control this.

The built in 'open' returns a file object.  The fileno() method of file
objects returns the file descriptor if you really need it.  File objects
have a wealth of methods explained in section 2.1.7.9 of the Library
Reference.  One of them is 'close()' which flushes buffers and closes the
file.  It also deallocates the file object.

Your example would then have to be:

my_file = open('file')
contents = my_file.readlines()

# Use the file object in any other way you need here.

my_file.close()

-Doug-




More information about the Python-list mailing list