Python“ with”示例语句

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 management

    EXPRESSION是将在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!')
with Statement File Operations
with Statement File Operations
与语句文件操作

最后尝试与声明(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()
LEARN MORE  What Is Segmentation Faults and Causes?
了解更多什么是细分错误和原因?

翻译自: https://www.poftut.com/python-with-statement-by-examples/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值