filehandle在Python超出范围后会自动关闭吗? [英] Does filehandle get closed automatically in Python after it goes out of scope?

查看:216
本文介绍了filehandle在Python超出范围后会自动关闭吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  def read_contents file_path)
返回文件(file_path).read()

如果不如何自动关闭这个函数?

解决方案

应该关闭文件的 __ del __ 语句,但更好的方法是使用块:



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $






$ code>

请参阅 http://docs.python.org/library/stdtypes.html#file.close 获取更多信息。


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?

解决方案

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()

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

这篇关于filehandle在Python超出范围后会自动关闭吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆