python读取文件with open_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 –

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值