我知道有很多關於在python中讀取文件的文章和問題。但我仍然想知道是什麼讓Python有多種方式來完成相同的任務。簡單地說,我想知道的是,使用這兩種方法的性能影響是什麼?使用「open()」vs「with open()」讀取文件「
8
A
回答
18
使用with
聲明未對性能增益,我不認爲有使用with
聲明,只要你執行相同的清潔活動,使用with
聲明將自動執行相關的任何性能收益或損失。
當您使用with
語句和open
函數時,您不需要在最後關閉文件,因爲with
會自動關閉它。
另外,with
聲明不僅僅是用於打開文件,而是與上下文管理器結合使用。基本上,如果您有一個對象想要確保一旦您完成清理或發生了某種錯誤,則可以將其定義爲context manager和with
語句將在進入時調用它的__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
相關問題
- 1. Like Open with Open圖
- 2. SendTo/Open With
- 3. Python - with open()except(FileNotFoundError)?
- 4. Movable Type:Pro vs Open
- 5. 文件不能使用open()
- 6. 使用Open Weather提供的Swift-2逐行讀取JSON文件
- 7. 無法在Python 2.7.4中使用open(sys.argv [])讀取文件
- 8. Spring Open with OpenShift獲取公開的URL
- 9. 讀取IOS中的Open-XML文檔
- 10. Rails:使用「Open With」選項下載文件
- 11. 如何使用Python中的「with open」打開多個文件?
- 12. 「Open with」選項通過vbscript
- 13. 通過open()。read()vs將其存儲在變量中讀取文件
- 14. 使用Open XML讀取已打開的Word文檔?
- 15. 寫作使用open(「文件」,「R」)
- 16. VS中的OPEN/EDIT果園
- 17. Ruby open-uri文件鎖定
- 18. open()無法打開文件
- 19. Linux open()文件描述符
- 20. grDevices保存文件open
- 21. android open sharedPreference xml文件
- 22. if callable throws timeoutexception java with streams open
- 23. iOS相冊「Open with ...」對話API?
- 24. 找到Finder中的「Open With」菜單項
- 25. Windows在哪裏存儲「Open With」設置?
- 26. 當我們在文件上使用「open with」時,它提供了什麼參數?
- 27. 如何使open()截斷現有文件
- 28. 我是否可以使用'open'只讀取和覆蓋一次?
- 29. 用open-uri打開本地文件
- 30. 使用「with open()as file」方法,如何多次寫入?
這個問題已經被問SO – The6thSense
上下文管理遠遠晚於純粹'的open()'方法進行了介紹。你可以用'timeit.timeit()'方法來衡量性能。 ''上下文管理器只是在任何失敗時釋放資源,所以你不必寫明確的'finally'子句。 –