程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python notes - with as statement

編輯:Python

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved