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



_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to