Python with and Pythonwith

Source: Internet
Author: User

Python with and Pythonwith

In Python, The with keyword is a good thing for you to manage and implement context protocol objects. For example, file. Example:

from __future__ import with_statement with open('cardlog.txt','r') as item :   for line in item :     print line; 

 
At the end of the file, the file handle is automatically closed.
 
In python2.6, with officially becomes a keyword.
So before python2.5, to use with, you need to use:

from __future__ import with_statement 

 
The principle is as follows:
All objects that implement the context Protocol include the following three methods:
_ Context _ () It returns a self-managed context object or a real context manager.
 
_ Enter () _ enter the context manager and start iteration.
 
When the with statement ends, whether it ends normally or throws an exception, _ exit _ () is executed. This method is used to close the resource connection.


Python withas

With open('abc.txt ', 'R') as f:
Balabalabala

Equivalent
Try:
F = open('abc.txt ', 'R ')
Except t:
Pass
Else:
Balabalabala
Finally:
F. close ()
Is the syntax much simpler?

Usage of while in python

L = [1, 2, 4, 8, 16, 32, 64] # define a list
X = 5 # assign 5 to x (so that x is global)
Found = I = 0 # assign 0 to found and I
While not found and I <len (L): (this sentence is not fully understood) ### meaning if found is false and the value of I is within the length of L, It loops
If 2 ** x = L [I]: (L [I]) ### L [I] indicates taking the I value of L, L [0] is 1, L [2] is 4, L [3] gets 8
Found = 1 (do not understand) ### assign 1 to the variable found
Else:
I = I + 1 (I have encountered this problem multiple times, but I don't understand it) ## it means I increase by 1. If I is 1 before execution, I equals 2 after execution.
If found: (what is a found?) ### if I is true (not equal to 0, it is true), print the following
Print 'at Index', I # output string 'at Index' and I-person value
Else: ### if I is false
Print x, 'not found' # output the value and string 'not found' of x'

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.