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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31334061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:50:16  来源:igfitidea点击:

File read using "open()" vs "with open()"

pythonperformancefile-io

提问by Chamath

I know there are plenty of articles and questions answered regarding reading files in python. But still I'm wondering what made python to have multiple ways to do the same task. Simply what I want to know is, what is the performance impact of using these two methods?

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

采纳答案by Anand S Kumar

Using withstatement is not for performance gain, I do not think there are any performance gains or loss associated with using withstatement, as long as, you perform the same cleanup activity that using withstatement would perform automatically.

Usingwith语句不是为了性能提升,我不认为有任何与 usingwith语句相关的性能提升或损失,只要您执行 usingwith语句将自动执行的相同清理活动。

When you use withstatement with openfunction, you do not need to close the file at the end, because withwould automatically close it for you.

当您使用with带有open函数的语句时,您不需要在最后关闭文件,因为with会自动为您关闭它。

Also, withstatement is not just for openning files, with is used in conjuction with context managers. Basically, if you have an object that you want to make sure it is cleaned once you are done with it or some kind of errors occur, you can define it as a context managerand withstatement will call its __enter__()and __exit__()methods on entry to and exit from the with block. According to PEP 0343-

此外,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.

此 PEPwith向 Python 语言添加了一个新语句“ ”,以便可以排除 try/finally 语句的标准用法。

在这个PEP,上下文管理器提供__enter__()__exit__()方法,这些方法与声明进入和退出的身体调用。

Also, performance testing of using withand not using it -

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