Is a with on open always necessary?

K Richard Pixley rich at noir.com
Wed Jan 25 12:12:59 EST 2012


On 1/20/12 07:44 , Andrea Crotti wrote:
> I normally didn't bother too much when reading from files, and for example
> I always did a
>
> content = open(filename).readlines()
>
> But now I have the doubt that it's not a good idea, does the file
> handler stays
> open until the interpreter quits?
>
> So maybe doing a
>
> with open(filename) as f:
> contents = f.readlines()
>
> is always a better idea??

It's a better idea when possible.

Sometimes the descriptor is opened in one method and closed in another. 
  In that case, "with" isn't possible.

--rich



More information about the Python-list mailing list