异常退出期间文件是否关闭? [英] Do files get closed during an exception exit?

查看:62
本文介绍了异常退出期间文件是否关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于异常而退出脚本时,打开的文件(和其他资源)会自动关闭吗?

Do open files (and other resources) get automatically closed when the script exits due to an exception?

我想知道在异常处理期间是否需要关闭资源.

I'm wondering if I need to be closing my resources during my exception handling.

编辑:更具体地说,我正在脚本中创建一个简单的日志文件.我想知道是否在异常情况下是否需要关注显式关闭日志文件. 由于我的脚本有一个复杂的,嵌套的try/except块,因此这样做有些复杂,因此如果在脚本崩溃/出错时python,CLIB或OS将要关闭我的文本文件,我不想在确保关闭文件上浪费了太多时间.

EDIT: to be more specific, I am creating a simple log file in my script. I want to know if I need to be concerned about closing the log file explicitly in the case of exceptions. since my script has a complex, nested, try/except blocks, doing so is somewhat complicated, so if python, CLIB, or the OS is going to close my text file when the script crashes/errors out, I don't want to waste too much time on making sure the file gets closed.

如果Python手册中有涉及这一部分的内容,请向我介绍,但我找不到它.

If there is a part in Python manual that talks about this, please refer me to it, but I could not find it.

推荐答案

不,他们没有.

即使在发生异常的情况下也要关闭文件,请使用with语句.

Use with statement if you want your files to be closed even if an exception occurs.

来自文档:

with语句用于包装具有以下内容的块的执行: 上下文管理器定义的方法.这使得普通 尝试...除外...最终使用模式将被封装以方便重用.

The with statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.

来自文档:

with语句允许使用诸如文件之类的对象,以确保始终及时,正确地清理它们.

 The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.

with open("myfile.txt") as f:
    for line in f:
        print line,

语句执行后,即使处理行时遇到问题,文件f也始终关闭.提供预定义清除操作的其他对象将在其文档中对此进行说明.

After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. Other objects which provide predefined clean-up actions will indicate this in their documentation.

这篇关于异常退出期间文件是否关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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