Python provides with
statements in order to exception and resource handling. There is already exception and resource handling features in Python but by using with
it is accomplished more elegant and clear way.
Python提供了with
语句,以便进行异常和资源处理。 Python中已经有异常和资源处理功能,但是通过with
使用with
可以实现更优雅,更清晰的方式。
与语句用法 (with Statement Usage)
with statement can be used in different cases. We will list the most popular with
statement usage in Python.
with语句可以在不同情况下使用。 我们将列出最流行的with
在Python语句用法。
- `File Handling` 文件处理
- `Exception Handling``异常处理`
- `Management of unmanaged resources` `非托管资源的管理`
带有语句语法 (with Statement Syntax)
with statement has very different syntax according to the other Python statements and keywords.
根据其他Python语句和关键字,with语句的语法非常不同。
with EXPRESSION as VARIABLE:
CODE-BLOCK
- `with` is the keyword “ with”是关键字
- `EXPRESSION` is the expression which will run inside the with for exception handling and resource managementEXPRESSION是将在with中运行的表达式,用于异常处理和资源管理
- `VARIABLE` is optional but used to create a variable from the EXPRESSION which will be used inside the CODE-BLOCK“ VARIABLE”是可选的,但用于从EXPRESSION创建变量,该变量将在CODE-BLOCK内部使用
- `CODE-BLOCK` is the code block where with statement is created. VARIABLE only available inside this code block. CODE-BLOCK also creates a block where resource and exceptions are automatically handled `CODE-BLOCK`是在其中创建with语句的代码块。 VARIABLE仅在此代码块内可用。 CODE-BLOCK还会创建一个自动处理资源和异常的块
与语句文件操作(with Statement File Operations)
One of the most popular use cases for the with statement is file operations like open, read, write, etc. We can open a file in a secure manner by using with
helping exception handling and resource management. Even we do not close the opened file with statement will handle it and close the file.
with语句最流行的用例之一是文件操作,例如打开,读取,写入等。我们可以通过帮助异常处理和资源管理来with
安全的方式打开文件。 即使我们不使用语句关闭打开的文件,也将处理它并关闭文件。
with open('test.c','w') as file:
file.write('hello world!')
最后尝试与声明(Try-Finally vs with Statement)
As stated previously with
statement can function like try-finally statements in order to catch exceptions. Here we will compare the try-finally and with
statements each other.
如前所述, with
语句可以像try-finally语句一样起作用,以捕获异常。 在这里,我们将比较try-finally和with
语句。
with open('test.c','w') as file:
file.write('hello world!')
OR
要么
file = open('file_path', 'w')
try:
file.write('hello world')
finally:
file.close()
翻译自: https://www.poftut.com/python-with-statement-by-examples/