As I understand it, with gives you a cleaner way of doing the following steps:<div><br></div><div>1) pre processing</div><div>2) actual work</div><div>3) post processing, where the __enter__ and __exit__ methods are used to take care of 1 and 3.</div>
<div><br></div><div>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__) .</div>
<div><br></div><div>I have just learned about it myself , so hopefully if I am not accurate someone more experienced can provide you with more detail.<br><br><div class="gmail_quote">On Fri, Jan 20, 2012 at 10:44 AM, Andrea Crotti <span dir="ltr"><<a href="mailto:andrea.crotti.0@gmail.com">andrea.crotti.0@gmail.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">I normally didn't bother too much when reading from files, and for example<br>
I always did a<br>
<br>
content = open(filename).readlines()<br>
<br>
But now I have the doubt that it's not a good idea, does the file handler stays<br>
open until the interpreter quits?<br>
<br>
So maybe doing a<br>
<br>
with open(filename) as f:<br>
     contents = f.readlines()<br>
<br>
is always a better idea??<span class="HOEnZb"><font color="#888888"><br>
-- <br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/<u></u>mailman/listinfo/python-list</a><br>
</font></span></blockquote></div><br></div>