python关键字“with”用于什么?

2024-03-29 13:09:30 发布

您现在位置:Python中文网/ 问答频道 /正文

python关键字“with”用于什么?

示例来自:http://docs.python.org/tutorial/inputoutput.html

>>> with open('/tmp/workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

Tags: orghttp示例docsreaddatahtmlas
2条回答

在python中,with关键字用于处理非托管资源(如文件流)。它类似于VB.NET和C中的using语句。它允许您确保在使用资源的代码完成运行时“清理”该资源,即使抛出异常。它为try/finally块提供“语法糖”。

来自Python Docs

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

更新根据Scott Wisniewski的评论修复了VB标注。我确实把withusing搞混了。

Explanation from the Preshing on Programming blog

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

相关问题 更多 >