文件句柄超出范围后是否会在 Python 中自动关闭?

发布时间:2023-03-07 / 作者:清心寡欲
本文介绍了文件句柄超出范围后是否会在 python 中自动关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I do the following, does filehandle get closed automatically as it goes out of scope in Python:

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

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

If it doesn't, how can I write this function to close the scope automatically?

推荐答案

它应该在文件的 __del__ 语句中关闭文件句柄,但更好的方法是使用 with 块:

It should close the file handle in the file's __del__ statement, but a better approach would be to use a with block:

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

参见 http://docs.python.org/library/stdtypes.html#file.close 了解更多信息.

See http://docs.python.org/library/stdtypes.html#file.close for more information.

这篇关于文件句柄超出范围后是否会在 Python 中自动关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持吉威生活!



[英文标题]Does filehandle get closed automatically in Python after it goes out of scope?


声明:本媒体部分图片、文章来源于网络,版权归原作者所有,如有侵权,请联系QQ:330946442删除。