Do files get closed during an exception exit?

前端 未结 4 1244
南笙
南笙 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:46

    Yes they do.

    This is a CLIB (at least in cpython) and operating system thing. When the script exits, CLIB will flush and close all file objects. Even if it doesn't (e.g., python itself crashes) the operating system closes its resources just like any other process. It doesn't matter if it was an exception or a normal exit or even if its python or any other program.

    Here's a script that writes a file and raises an exception before the file contents have been flushed to disk. Works fine:

    ~/tmp/so$ cat xyz.txt
    cat: xyz.txt: No such file or directory
    ~/tmp/so$ cat exits.py
    f = open("xyz.txt", "w")
    f.write("hello")
    print("file is", open("xyz.txt").read())
    assert False
    
    ~/tmp/so$ python exits.py
    ('file is', '')
    Traceback (most recent call last):
      File "exits.py", line 4, in 
        assert False
    AssertionError
    ~/tmp/so$ cat xyz.txt
    hello
    

提交回复
热议问题