使用“open()"读取文件与“使用 open()" [英] File read using "open()" vs "with open()"
问题描述
我知道有很多关于在 python 中读取文件的文章和问题的回答.但我仍然想知道是什么让 python 有多种方法来完成相同的任务.我只想知道,使用这两种方法对性能的影响是什么?
I know there are plenty of articles and questions answered regarding reading files in python. But still I'm wondering what made python to have multiple ways to do the same task. Simply what I want to know is, what is the performance impact of using these two methods?
推荐答案
使用 with
语句不是为了性能提升,我认为使用 不会带来任何性能提升或损失with
语句,只要您执行使用 with
语句自动执行的相同清理活动.
Using with
statement is not for performance gain, I do not think there are any performance gains or loss associated with using with
statement, as long as, you perform the same cleanup activity that using with
statement would perform automatically.
当你使用with
语句和open
函数时,最后不需要关闭文件,因为with
会自动关闭给你.
When you use with
statement with open
function, you do not need to close the file at the end, because with
would automatically close it for you.
此外,with
语句不仅仅用于打开文件,with 还与上下文管理器结合使用.基本上,如果你有一个对象,你想确保它在完成后被清理或发生某种错误,你可以将它定义为 context manager 和 with
语句会调用它的 __enter__()
和 __exit__()
进入和退出 with 块的方法.根据 PEP 0343 -
Also, with
statement is not just for openning files, with is used in conjuction with context managers. Basically, if you have an object that you want to make sure it is cleaned once you are done with it or some kind of errors occur, you can define it as a context manager and with
statement will call its __enter__()
and __exit__()
methods on entry to and exit from the with block. According to PEP 0343 -
此 PEP 添加了一个新语句with
";到 Python 语言,以便可以排除 try/finally 语句的标准用法.
This PEP adds a new statement "
with
" to the Python language to make it possible to factor out standard uses of try/finally statements.
在这个 PEP 中,上下文管理器提供了 __enter__()
和 __exit__()
方法,这些方法在进入和退出 with 语句的主体时被调用.>
In this PEP, context managers provide __enter__()
and __exit__()
methods that are invoked on entry to and exit from the body of the with statement.
另外,使用with
和不使用它的性能测试-
Also, performance testing of using with
and not using it -
In [14]: def foo():
....: f = open('a.txt','r')
....: for l in f:
....: pass
....: f.close()
....:
In [15]: def foo1():
....: with open('a.txt','r') as f:
....: for l in f:
....: pass
....:
In [17]: %timeit foo()
The slowest run took 41.91 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 186 µs per loop
In [18]: %timeit foo1()
The slowest run took 206.14 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 179 µs per loop
In [19]: %timeit foo()
The slowest run took 202.51 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 180 µs per loop
In [20]: %timeit foo1()
10000 loops, best of 3: 193 µs per loop
In [21]: %timeit foo1()
10000 loops, best of 3: 194 µs per loop
这篇关于使用“open()"读取文件与“使用 open()"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!