Is a with on open always necessary?

Justin Simms justin.simms at
Fri Jan 20 10:49:31 EST 2012

As I understand it, with gives you a cleaner way of doing the following

1) pre processing
2) actual work
3) post processing, where the __enter__ and __exit__ methods are used to
take care of 1 and 3.

So with is not always necessary, but it is the preferred was to do things
like file processing, since the file object and other already have the
context manager protocol in place (which is when the object being used in
the with expression has implementations of __with__ and __exit__) .

I have just learned about it myself , so hopefully if I am not accurate
someone more experienced can provide you with more detail.

On Fri, Jan 20, 2012 at 10:44 AM, Andrea Crotti
<andrea.crotti.0 at>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??
> --
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list