我知道有很多关于在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. 使用时with..open
- 3. iOS“Open With ...”ZIP文件
- 4. SendTo/Open With
- 5. CameraCalibration with Open CV
- 6. SyntaxError using`with open ...`
- 7. os.open vs open,使用什么
- 8. Nav with JS(double open)
- 9. Python - with open()except(FileNotFoundError)?
- 10. emacs如何为文件选择“open-with”?
- 11. Open LDAP vs apacheDS
- 12. Movable Type:Pro vs Open
- 13. QDialog:show()vs open()
- 14. 文件不能使用open()
- 15. 我可以使用Open Xml读取RTF和Doc文件吗?
- 16. 使用Open Weather提供的Swift-2逐行读取JSON文件
- 17. 无法在Python 2.7.4中使用open(sys.argv [])读取文件
- 18. 使用Open XML SDK读取已上传的pptx文件
- 19. Spring Open with OpenShift获取公开的URL
- 20. 读取IOS中的Open-XML文档
- 21. 如何使用Python中的“with open”打开多个文件?
- 22. Rails:使用“Open With”选项下载文件
- 23. Ruby open-uri open方法丢失文件扩展名open images
- 24. “Open with”选项通过vbscript
- 25. Ruby Open-URI with Dynamic Website
- 26. 通过open()。read()vs将其存储在变量中读取文件
- 27. 使用Open XML读取已打开的Word文档?
- 28. VS中的OPEN/EDIT果园
- 29. 写作使用open(“文件”,“R”)
- 30. 在sitemap.xml中使用BeautifulSoup open .gz文件
这个问题已经被问SO – The6thSense
上下文管理远远晚于纯粹'的open()'方法进行了介绍。你可以用'timeit.timeit()'方法来衡量性能。 ''上下文管理器只是在任何失败时释放资源,所以你不必写明确的'finally'子句。 –