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