with as The main functions of the statement are as follows :
The first is to solve the problem of resource release during abnormal exit ;
The second is to solve the problem that users forget to call close Resource leakage caused by method .
There are some tasks , It may need to be set up beforehand , Clean up afterwards . For this scenario ,Python Of with Statements provide a very convenient way to do this . A good example is file processing , You need to get a file handle , Reading data from a file , Then close the file handle .
If not with sentence , The code is as follows :
file = open("/tmp/foo.txt")
data = file.read()
file.close()
Here are two questions . One is that you may forget to close the file handle ; Second, the file read data is abnormal , There was no treatment . Here is an enhanced version of handling exceptions :
file = open("/tmp/foo.txt")
try:
data