'with open(file):' 和手动 opening/closing 之间的性能差异
Performance difference between 'with open(file):' and just opening/closing it manually
我想每个人都会同意
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')
就性能而不是安全而言,手册opening/closing不是更好吗?代码处理起来肯定更短,而且没有缩进。有人能解释一下为什么人们甚至使用安全代码 with open(file)
吗?
这是 python 惯例。没有有意义的性能差异。
此外,您不确定该文件将始终关闭。 f.write('something')
线可能会爆炸。
我想每个人都会同意
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')
就性能而不是安全而言,手册opening/closing不是更好吗?代码处理起来肯定更短,而且没有缩进。有人能解释一下为什么人们甚至使用安全代码 with open(file)
吗?
这是 python 惯例。没有有意义的性能差异。
此外,您不确定该文件将始终关闭。 f.write('something')
线可能会爆炸。