2015-07-10 65 views
8

我知道有很多关于在python中读取文件的文章和问题。但我仍然想知道是什么让Python有多种方式来完成相同的任务。简单地说,我想知道的是,使用这两种方法的性能影响是什么?使用“open()”vs“with open()”读取文件“

+0

这个问题已经被问SO – The6thSense

+4

上下文管理远远晚于纯粹'的open()'方法进行了介绍。你可以用'timeit.timeit()'方法来衡量性能。 ''上下文管理器只是在任何失败时释放资源,所以你不必写明确的'finally'子句。 –

回答

18

使用with声明未对性能增益,我不认为有使用with声明,只要你执行相同的清洁活动,使用with声明将自动执行相关的任何性能收益或损失。

当您使用with语句和open函数时,您不需要在最后关闭文件,因为with会自动关闭它。

另外,with声明不仅仅是用于打开文件,而是与上下文管理器结合使用。基本上,如果您有一个对象想要确保一旦您完成清理或发生了某种错误,则可以将其定义为context managerwith语句将在进入时调用它的__enter__()__exit__()方法,以及从with block退出。据PEP 0343 -

这PEP增加了一个新说法“with” Python语言,以使其能够分解出的try/finally语句的标准使用。

在这个PEP中,上下文管理器提供__enter__()__exit__()方法,这些方法在进入和离开with语句的主体时被调用。

此外,使用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