2015-07-10 70 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