python读取文件with open_关于python:使用”open()”vs”with open()”读取文件

本问题已经有最佳答案,请猛点这里访问。

我知道有很多关于用python读取文件的文章和问题得到了解答。但我仍然想知道是什么让Python有多种方法来完成相同的任务。我只想知道,使用这两种方法对性能有什么影响?

这个问题已经问过了,所以

上下文管理器的引入比纯open()方法晚得多。您可以使用timeit.timeit()方法测量性能。with上下文管理器只在任何失败时释放资源,因此您不必编写显式的finally子句。

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

当使用带open功能的with语句时,不需要在文件末尾关闭文件,因为with会自动为您关闭文件。

另外,with语句不仅用于打开文件,还与上下文管理器结合使用。基本上,如果您有一个对象想要确保它在完成操作后被清除,或者发生某种错误,您可以将它定义为上下文管理器,并且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而不使用它的性能测试-

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30In [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、付费专栏及课程。

余额充值