File read using “open()” vs “with open()”
本问题已经有最佳答案,请猛点这里访问。
我知道有很多关于用python读取文件的文章和问题得到了解答。但我仍然想知道是什么让Python有多种方法来完成相同的任务。我只想知道,使用这两种方法对性能有什么影响?
使用
当使用带
另外,
This PEP adds a new statement"
with " to the Python language to make it possible to factor out standard uses of try/finally statements.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.
另外,使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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 |