大佬教程收集整理的这篇文章主要介绍了使用“ open()”和“ with open()”读取文件,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
using@H_404_1@with语句不是为了提高性能,@H_404_1@with只要您执行与using@H_404_1@with语句将自动执行的相同的清除活动,我认为与using语句不存在任何性能提升或损失。
当您将@H_404_1@with带有@H_404_1@open功能的语句一起使用时,不需要最后关闭文件,因为@H_404_1@with它将自动为您关闭文件。
此外,@H_404_1@with语句不仅用于打开文件,还与上下文管理器结合使用。基本上,如果您有一个要确保在完成操作后便将其清除或发生某种错误的对象,则可以将其定义为上下文管理器,并且@H_404_1@with语句将在进入和退出时调用@H_404_1@__enter__()和@H_404_1@__exit__()方法with块。根据PEP 0343 -
另外,对使用@H_404_1@with和不使用它的性能进行测试-
@H_404_1@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文件的文章和回答的问题。但是我仍然想知道是什么使python具有多种方法来完成相同的任务。我只想知道,使用这两种方法对性能有何影响?
以上是大佬教程为你收集整理的使用“ open()”和“ with open()”读取文件全部内容,希望文章能够帮你解决使用“ open()”和“ with open()”读取文件所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。