使用Python的“with”带有 try- except 块的语句

发布于 2024-09-17 00:04:40 字数 562 浏览 3 评论 0原文

这是将 python“with”语句与 try- except 块结合使用的正确方法吗?:

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

如果是,那么考虑旧的做事方式:

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

这里“with”语句的主要好处是我们可以摆脱三行代码?对于这个用例来说,这对我来说似乎没有那么引人注目(尽管我知道“with”语句还有其他用途)。

编辑:上述两个代码块的功能是否相同?

EDIT2:前几个答案一般谈论使用“with”的好处,但这些在这里似乎是边际效益。多年来我们都(或应该)显式调用 f.close() 。我认为一个好处是,草率的程序员会从使用“with”中受益。

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".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦途 2024-09-24 00:04:40
  1. 您给出的两个代码块是
    等效
  2. 您描述为旧方式的代码
    的做事
    有一个严重的bug:
    如果打开文件失败
    将得到第二个异常
    finally 子句,因为 f 不是
    边界。

等效的旧式代码如下:

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

如您所见,with 语句可以减少出错的可能性。在较新版本的 Python(2.7、3.1)中,您还可以在一个 with 语句中组合多个表达式。例如:

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

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

  1. The two code blocks you gave are
    not equivalent
  2. The code you described as old way
    of doing things
    has a serious bug:
    in case opening the file fails you
    will get a second exception in the
    finally clause because f is not
    bound.

The equivalent old style code would be:

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())

Besides that, I personally regard it as bad habit to catch any exception as early as possible. This is not the purpose of exceptions. If the IO function that can fail is part of a more complicated operation, in most cases the IOError should abort the whole operation and so be handled at an outer level. Using with statements, you can get rid of all these try...finally statements at inner levels.

吹泡泡o 2024-09-24 00:04:40

如果finally块的内容是由正在打开的文件对象的属性决定的,为什么文件对象的实现者不应该是编写finally的人堵塞? 就是 with 语句的好处,远不止在此特定实例中节省三行代码。

是的,将 withtry- except 结合起来的方式几乎是唯一的方法,因为 open 中会导致异常错误code> 语句本身无法在 with 块中捕获。

If the contents of the finally block are determined by the properties of the file object being opened, why shouldn't the implementer of the file object be the one to write the finally block? That's the benefit of the with statement, much more than saving you three lines of code in this particular instance.

And yes, the way you've combined with and try-except is pretty much the only way to do it, as exceptional errors caused within the open statement itself can't be caught within the with block.

岁月静好 2024-09-24 00:04:40

我认为你对“with”语句的理解是错误的,它只会减少行数。
它实际上进行初始化并处理拆卸。

在您的情况下,“with”确实

  • 打开一个文件,
  • 处理其内容,并
  • 确保关闭它。

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

编辑:是的,您对“with”的使用是正确的,并且两个代码块的功能是相同的。
关于为什么使用“with”的问题?这是因为你从中获得的好处。就像你提到的不小心错过了 f.close() 。

I think you got it wrong about "with" statement that it only reduces lines.
It actually does initialization and handle teardown.

In your case "with" does

  • open a file,
  • process its contents, and
  • make sure to close it.

Here is link for understanding "with" statement : 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.
Question about why to use "with" ? it's because of benefits you get with it. like you mentioned about accidentally missing f.close().

熟人话多 2024-09-24 00:04:40

下面的代码更Pythonic的方式是:

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()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文