[Tutor] reading lines from a list of files

Laura Creighton lac at openend.se
Thu May 14 09:15:42 CEST 2015


In a message of Wed, 13 May 2015 22:27:11 -0700, Alex Kleider writes:
>As a follow up question:
>The following seems to work-
>
>     for f_name in list_of_file_names:
>         for line in open(f_name, 'r'):
>             process(line)
>
>but should I be worried that the file doesn't get explicitly closed?
>
>Alex

If you use the with statement you will guarantee that the file closes
as soon as you are done with it. It will also handle exceptions nicely for you.
See: https://www.python.org/dev/peps/pep-0343/

In practice, Cpython's ref counting semantics means that running out
of file descriptors doesn't happen (unless you put that code in a
loop that gets called a whole lot).  But the gc used by a Python
version is not part of the language specification, but is a
language implementation detail.  If you are writing for PyPy or
Jython you will need to use the with statement or close your files
explicitly, so the gc knows you are done with them.  Relying on
'the last reference to them went away' to close your file won't
work if the gc isn't counting references.

See: http://pypy.org/compat.html
or for more detail: http://pypy.readthedocs.org/en/latest/cpython_differences.html#differences-related-to-garbage-collection-strategies

Laura





More information about the Tutor mailing list