python – 使用“open()”vs“with open()”读取文件
参见英文答案 >
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 –
此外,使用和不使用它的性能测试 – 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |