python - 'with open(file):'与手动打开/关闭它之间的性能差异

标签 python file error-handling with-statement try-finally

我想每个人都会同意

with open(file_name, 'mode') as f:
    #do things with f

比...更好
f = open(file_name, 'mode')
#do things with f
f.close()

http://effbot.org/zone/python-with-statement.htm我们可以阅读

When the “with” statement is executed, Python evaluates the expression, calls the enter method on the resulting value (which is called a “context guard”), and assigns whatever enter returns to the variable given by as. Python will then execute the code body, and no matter what happens in that code, call the guard object’s exit method.



换句话说,with具有类似于结构的
def controlled_execution():
    set things up
    try:
        yield thing
    finally:
        tear things down

for thing in controlled_execution():
    do something with thing

知道 :

The try-finally construct guarantees that the "finally" part is always executed, even if the code that does the work doesn’t finish.



因此,一旦打开文件,无论发生什么情况,它也会被关闭,从而避免了文件在我们不知情的情况下保持打开的可能性,并返回如下错误:

Error: Windows32 | ERROR_SHARING_VIOLATION 32 (0x20) | The process cannot access the file because it is being used by another process.



如果对同一文件进行操作。

我不想太离题,所以我会直接讲到重点,
如果我有一个简单的代码,可以确定
知道,则文本文件将关闭(编辑:感谢现在回答,我知道我们不能确定)
f = open(file_name, 'w')
f.write('something')
f.close()

和REAL 有什么区别
with open(file_name, 'w') as f:
    f.write('something')

就性能而不是安全而言,手动打开/关闭不是更好吗?该代码肯定更短,而且没有缩进。有人可以解释一下为什么即使在安全密码下人们也使用with open(file)吗?

最佳答案

这是python约定。没有有意义的性能差异。

此外,您不确定该文件将始终关闭。 f.write('something')行可能会爆炸。

关于python - 'with open(file):'与手动打开/关闭它之间的性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33330294/

相关文章:

python - 字符串乘法与 for 循环

node.js - 如何处理 Node.js 中的异步错误

php - 如何在 MAMP 上显示错误?

python - Pandas:有条件地用集合替换

python - 多维 ndarray 的 argsort

c++ - 从 Cpp 中的 URL 下载时获取空的 CSV

python - 创建一个新文件,文件名包含循环变量,python

file - Map在Hadoop下运行时应该把临时文件放在哪里

vba - 组合框的无效属性值

python - 将数据帧转换为不带括号的记录列表