为什么`with open()` 更适合在 Python 中打开文件? [英] Why is `with open()` better for opening files in Python?

查看:37
本文介绍了为什么`with open()` 更适合在 Python 中打开文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经常当有人发布他们的代码时,人们会在旁边添加你现在应该使用 with open('filename') as f 语法".我同意大多数老式的 f = open() 语句没有伴随的 .close(),我什至回答了这种依赖的问题隐式关闭"是他们编程问题的全部原因.

Frequently when someone posts their code, people will add as an aside that "you should use with open('filename') as f syntax now." I agree that most of the old-fashioned f = open() statements don't have an accompanying .close(), and I have even answered questions where this reliance on "implicit close" was the entire cause of their programming problem.

但是,在某些情况下,将代码嵌套在 with 块中似乎会给编写代码带来其他不便.例如,我有时喜欢在开头使用一个标志来表示 writefile = True.这让我只打开和关闭要使用的文件,同时保持相同的处理线程.在代码的不同位置,我可以打印到屏幕或写入文件.(我意识到我会在开头打开 stdout 或文件并改用这种方法.)

However, in some cases nesting your code inside the with block seems to create other inconveniences in writing the code. For example I sometimes like to use a flag at the beginning to say writefile = True. This lets me only open and close the file if it is going to be used, while keeping the same processing thread. At various places in the code I can either print to screen or write to a file. (I realize I would open stdout or the file at the beginning and use that approach instead.)

我的问题是:除了不必明确关闭文件之外,还有其他原因可以使用 with 语法来处理文件,尤其是输出文件吗?(More pythonic"本身并不是一个原因.)如果这是重复的,我很高兴指出这一点,但我自己找不到.

My question is: besides not having to explicitly close the file, are there other reasons to use the with syntax for handling files, especially output files? ("More pythonic" by itself is not a reason.) If this is a duplicate, I would be glad to have this pointed out, but I couldn't find it myself.

推荐答案

with 没有其他优势:确保清理是它唯一的用途.

There's no other advantage of with: ensuring cleanup is the only thing it's for.

无论如何您都需要一个作用域块,以便在发生异常时关闭文件:

You need a scoped block anyway in order to close the file in the event of an exception:

writefile = random.choice([True, False])
f = open(filename) if writefile else None
try:
    # some code or other
finally:
    if writefile:
        f.close()

因此,您描述的 with 的缺点实际上是正确代码的缺点(在需要清理的情况下),无论您如何编写.

So, the thing you describe as a disadvantage of with is really a disadvantage of correct code (in the case where cleanup is required), no matter how you write it.

这篇关于为什么`with open()` 更适合在 Python 中打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆