Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 文件读取使用";打开();vs";使用open();_Python_Performance_File Io - Fatal编程技术网

Python 文件读取使用";打开();vs";使用open();

Python 文件读取使用";打开();vs";使用open();,python,performance,file-io,Python,Performance,File Io,我知道有很多关于阅读python文件的文章和问题得到了回答。但我仍然想知道是什么让python有多种方法来完成相同的任务。简单地说,我想知道的是,使用这两种方法对性能的影响是什么?使用with语句并不是为了提高性能,我不认为使用with语句会带来任何性能增益或损失,只要,您执行的清理活动与使用with语句自动执行的清理活动相同 当您使用with语句withopen函数时,您不需要在末尾关闭文件,因为with会自动为您关闭文件 另外,with语句不仅用于打开文件,还与上下文管理器结合使用。基本上,

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

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

当您使用
with
语句with
open
函数时,您不需要在末尾关闭文件,因为
with
会自动为您关闭文件

另外,
with
语句不仅用于打开文件,还与上下文管理器结合使用。基本上,如果您有一个对象,您想确保它在处理完后被清理干净,或者发生了某种错误,那么可以将它定义为一个,并且
with
语句将在进入和退出with块时调用它的
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu()
方法。据-

这个PEP在Python语言中添加了一个新语句“
with
”,以便能够排除try/finally语句的标准用法

在此PEP中,上下文管理器提供了
\uuuuuuuuuuuuuuuuuuuuuuuuuu()
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

另外,对使用
以及不使用它进行性能测试-

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

这个问题在SOContext Manager中已经被提出,它的引入要比纯
open()
方法晚得多。您可以使用
timeit.timeit()
方法测量性能
with
context manager只在出现任何故障时释放资源,因此您不必编写显式的
finally
子句。