Example of Pythonwith usage

Source: Internet
Author: User
This article mainly introduces Pythonwith usage examples. This article describes several usage methods and scenarios of with statements. if you need to use with statements, you can refer to with statements in python to significantly improve the code friendliness. for example:

The code is as follows:


With open('a.txt ') as f:
Print f. readlines ()


We can also use with for our own classes. just add two functions _ enter __, _ exit _ to this class:

The code is as follows:


>>> Class:
Def _ enter _ (self ):
Print 'in enter'
Def _ exit _ (self, e_t, e_v, t_ B ):
Print 'in exit'

>>> With A () as:
Print 'in'

In enter
In
In exit


In addition, the python library also has a contextlib module, so that you do not need to construct a class containing _ enter __, _ exit _ to use:

The code is as follows:


>>> From contextlib import contextmanager
>>> From _ future _ import with_statement
>>> @ Contextmanager
... Def context ():
... Print 'entering the zone'
... Try:
... Yield
... Failed t Exception, e:
... Print 'with an error % s' % e
... Raise e
... Else:
... Print 'with no error'
...
>>> With context ():
... Print '---- in context call ------'
...
Entering the zone
---- In context call ------
With no error


The most commonly used contextmanager, and another closing function is of little use.

The code is as follows:


From contextlib import closing
Import urllib

With closing (urllib. urlopen ('http: // www.python.org ') as page:
For line in page:
Print line

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.