Do files get closed during an exception exit?

前端 未结 4 1237
南笙
南笙 2020-12-03 03:08

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 03:41

    No, they don't.

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

    From the docs:

    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.

    From docs:

     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,
    

    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.

提交回复
热议问题