使用with语句不是为了提高性能,我不认为与使用with语句相关联的任何性能增益或损失,只要您执行的清理活动与使用with语句将自动执行的清理活动相同。
当您将with语句与open函数一起使用时,不需要在末尾关闭该文件,因为with将自动为您关闭该文件。
此外,with语句不仅用于打开文件,with还与上下文管理器结合使用。基本上,如果您有一个对象,希望确保在完成该对象或发生某种错误后将其清除,则可以将其定义为context manager,并且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和不使用它的性能测试-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