关于python:使用”open()”vs”with open()”读取文件

File read using “open()” vs “with open()”

本问题已经有最佳答案,请猛点这里访问。

我知道有很多关于用python读取文件的文章和问题得到了解答。但我仍然想知道是什么让Python有多种方法来完成相同的任务。我只想知道,使用这两种方法对性能有什么影响?


使用with语句不是为了提高性能,我认为使用with语句不会带来任何性能上的收益或损失,只要您执行的清理活动与使用with语句自动执行的清理活动相同。

当使用带open功能的with语句时,不需要在文件末尾关闭文件,因为with会自动为您关闭文件。

另外,with语句不仅用于打开文件,还与上下文管理器结合使用。基本上,如果您有一个对象想要确保它在完成操作后被清除,或者发生某种错误,您可以将它定义为上下文管理器,并且with语句将在进入和退出With块时调用它的__enter__()__exit__()方法。根据PEP 0343-

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.

另外,使用with而不使用它的性能测试-

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