[Tutor] reading lines from a list of files

Alan Gauld alan.gauld at btinternet.com
Thu May 14 09:01:44 CEST 2015


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.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list