ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – 使用“open()”vs“with open()”读取文件

2019-09-19 01:58:40  阅读:249  来源: 互联网

标签:python performance file-io


参见英文答案 > What is the python “with” statement designed for?                                    10个
我知道有很多关于在python中读取文件的文章和问题.但我仍然想知道是什么让python有多种方法来完成同样的任务.我想知道的是,使用这两种方法对性能有何影响?

解决方法:

使用with语句不是为了获得性能,我认为使用with语句不会产生任何性能上的提升或损失,只要您执行与使用with语句自动执行相同的清理活动.

当你使用带有open函数的语句时,你不需要在最后关闭文件,因为with会自动为你关闭它.

此外,with语句不仅适用于打开文件,还与上下文管理器结合使用.基本上,如果您有一个对象要确保在完成它之后清除它或发生某种错误,您可以将其定义为context manager并且with语句将调用其__enter __()和__exit __()方法在进入和退出with块时.根据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.

此外,使用和不使用它的性能测试 –

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

标签:python,performance,file-io
来源: https://codeday.me/bug/20190919/1811999.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有