[Tutor] Examples of "With....As Statement" in Python
mariocatch
mariocatch at gmail.com
Tue Jul 10 17:44:36 CEST 2012
On Tue, Jul 10, 2012 at 11:25 AM, Mark Lawrence <breamoreboy at yahoo.co.uk>wrote:
> On 10/07/2012 15:58, James Bell wrote:
>
>> I'm attempting to learn how to use the "with....as" statement in python.
>>
>> I've read the documentation and also a few tutorials but I still cannot
>> understand the concept. or how this is normally used. Can someone please
>> write an example or 2 of simple ways to use the "with statement".
>>
>> I understand in java the try...catch...finally block so maybe someone can
>> point out the relationship between them.
>>
>> thanks.
>> ______________________________**_________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>>
>>
> You're not the only one, see this http://effbot.org/zone/python-**
> with-statement.htm <http://effbot.org/zone/python-with-statement.htm>
>
> --
> Cheers.
>
> Mark Lawrence.
>
>
>
> ______________________________**_________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
The 'with' statement (
http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects).
'with' is not like a try/catch/finally. It is more like a using in .NET.
It's simply a way for you to create an instance of a disposable object, and
have it automatically cleaned up for you at the end of the 'with' statement.
Consider the following file usage:
f = open('test.txt', 'r')
f.read()
f.close()
Imagine if I forgot to close the file handler 'f'? Instead of worrying
about that, you can let python handle it for you:
with open('test.txt, 'r') as f:
f.read()
Now, when the 'with' statement ends, it will automatically dispose the file
object 'f' and close the stream for you.
-Mario
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120710/cf7b5c13/attachment-0001.html>
More information about the Tutor
mailing list