Using python "with" statement with try-except block

Is this the right way to use the python "with" statement in combination with a try-except block?:

try:
with open("file", "r") as f:
line = f.readline()
except IOError:
<whatever>

If it is, then considering the old way of doing things:

try:
f = open("file", "r")
line = f.readline()
except IOError:
<whatever>
finally:
f.close()

Is the primary benefit of the "with" statement here that we can get rid of three lines of code? It doesn't seem that compelling to me for this use case (though I understand that the "with" statement has other uses).

EDIT: Is the functionality of the above two blocks of code identical?

EDIT2: The first few answers talk generally about the benefits of using "with", but those seem of marginal benefit here. We've all been (or should have been) explicitly calling f.close() for years. I suppose one benefit is that sloppy coders will benefit from using "with".

97944 次浏览

如果 finally块的内容是由打开的文件对象的属性决定的,那么为什么文件对象的实现者不应该是编写 finally块的人呢?那是with语句的优点,比在这个特殊实例中节省三行代码要多得多。

是的,将 withtry-except结合起来的方法几乎是唯一的方法,因为 open语句本身引起的异常错误不能在 with块中捕获。

我觉得你把“ with”这个词理解错了,它只是减少了行数。 它实际上进行初始化和处理拆卸。

在你的情况下“与”做

  • open a file,
  • 处理其内容,以及
  • make sure to close it.

这里是理解“ with”语句的链接: http://effbot.org/zone/python-with-statement.htm

Edit: Yes your usage of "with" is correct and functionality of both blocks of code is identical. 关于为什么用“ with”的问题?而是因为你能从中得到好处。就像你提到的意外失踪的 F.close ()。

  1. 你给出的两个代码块是 不等同
  2. The code you described as old way 有一个严重的错误: 以防打开文件失败 将在 因为 f不是 约束。

相应的旧风格代码是:

try:
f = open("file", "r")
try:
line = f.readline()
finally:
f.close()
except IOError:
<whatever>

As you can see, the with statement can make things less error prone. In newer versions of Python (2.7, 3.1), you can also combine multiple expressions in one with statement. For example:

with open("input", "r") as inp, open("output", "w") as out:
out.write(inp.read())

除此之外,我个人认为尽早发现任何异常都是一个坏习惯。这不是例外的目的。如果可能失败的 IO 函数是更复杂操作的一部分,那么在大多数情况下,IOError 应该中止整个操作,因此应该在外部级别进行处理。使用 with语句,您可以在内部级别去掉所有这些 try...finally语句。

The more Pythonic way for the following codes is:

try:
f = open("file", "r")
try:
line = f.readline()
finally:
f.close()
except IOError:
<whatever>


try:
f = open("file", "r")
except IOError:
<whatever>
else:
f.close()