[Tutor] reading lines from a list of files

Alex Kleider akleider at sonic.net
Thu May 14 09:57:12 CEST 2015


On 2015-05-14 00:01, Alan Gauld wrote:
> On 14/05/15 06:27, Alex Kleider wrote:
> 
>> 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?
> 
> If you are only ever reading from the file then no, I'd not worry
> too much. But in the general case, where you might be making
> changes then yes, you should worry.
> 
> It will work 99% of the time but if things go wrong there's always
> a chance that a file has not been closed yet and your changes have
> not been written to the file. But if you are not changing the file
> it doesn't matter too much.
> 
> The only other consideration is that some OS might put a lock
> on the file even if it's only read access, so in those cases
> closing will release the lock sooner. But I don't think any of
> the popular OS do that any more.

Thank you, Alan; I hadn't appreciated the important difference in risk
with write vs read.  It's clear that 'best practice' would be to use
'with' so as to 'cover all bases.'


More information about the Tutor mailing list