python读取文件with open_使用“open()”与“with open()”读取文件

使用with语句不是为了提高性能,我不认为与使用with语句相关联的任何性能增益或损失,只要您执行的清理活动与使用with语句将自动执行的清理活动相同。

当您将with语句与open函数一起使用时,不需要在末尾关闭该文件,因为with将自动为您关闭该文件。

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

另外,使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值