Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.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
filehandle在Python中超出范围后是否会自动关闭?_Python_File_Scope - Fatal编程技术网

filehandle在Python中超出范围后是否会自动关闭?

filehandle在Python中超出范围后是否会自动关闭?,python,file,scope,Python,File,Scope,如果我执行以下操作,filehandle是否会在超出Python范围时自动关闭: def read_contents(file_path): return file(file_path).read() 如果没有,我如何编写此函数来自动关闭作用域?它应该关闭文件的\uuu del\uuu语句中的文件句柄,但更好的方法是使用和块: def read_contents(file_path): with open(file_path, 'r') as f: return f.read(

如果我执行以下操作,filehandle是否会在超出Python范围时自动关闭:

def read_contents(file_path):
  return file(file_path).read()

如果没有,我如何编写此函数来自动关闭作用域?

它应该关闭文件的
\uuu del\uuu
语句中的文件句柄,但更好的方法是使用
块:

def read_contents(file_path):
  with open(file_path, 'r') as f:
    return f.read()

有关更多信息,请参阅。

要展开FogleBird的回答,如果您没有明确关闭它,则当文件对象被销毁时,文件将自动关闭。在CPython中,一旦不再引用它,就会发生这种情况,例如,如果它是函数中的局部变量,并且函数结束。但是,如果在函数中引发异常,并且未使用
with
语句或
try:…finally:
显式关闭文件,则对该文件的引用将保留为回溯对象中堆栈跟踪的一部分,并且至少在引发下一个异常之前,不会关闭该文件

IronPython和Jython还分别使用.NETCLR和JavaJVM的垃圾收集功能。这些都不是引用计数的,因此在垃圾收集器决定回收对象内存或程序终止之前,文件将无限期保持打开状态

因此,通常使用
with:
try:…finally:
显式关闭文件非常重要


当然,对于需要显式清理的任何其他类型的对象,所有这些都适用。

只需提及:file返回具有close方法的file对象。这将是最直接的解决方案,但“with”显然是更好的解决方案。我有一个问题——我的Python中没有
with
。从未来进口可以吗?我有Python2.5。如果你有Python2.5,那么是的。谢谢。还有一个问题-如果我将我的应用程序转移到Python 2.6的安装中,从未来导入的
是否仍然有效?或者使用链接中描述的try/finally方法。“不麻烦”-我不知道这些:(还要注意:在Python3中,“至少在引发下一个异常之前,文件不会关闭”这一子句不再准确;在Python3中,引发新异常会隐式链接异常上下文,因此如果捕获一个异常并引发一个新异常,则原始异常的回溯将保留在新异常中(除非他们明确禁用了上下文,例如从None提升
)。在Py 2和Py 3中,通过回溯创建循环垃圾相当容易;即使不再引用异常,您也会等待循环GC清理,就像Jython一样。