[Tutor] reading lines from a list of files

Alex Kleider akleider at sonic.net
Thu May 14 09:52:16 CEST 2015


On 2015-05-14 00:15, Laura Creighton wrote:
> 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

Thanks, Laura, for your analysis.  I'll happily include the one extra 
line and
let 'with' do its magic rather than depend on implementation details (or 
  worry
about their shortcomings:-)



More information about the Tutor mailing list