Is explicitly closing files important?

前端 未结 6 668
野的像风
野的像风 2020-11-22 00:26

In Python, if you either open a file without calling close(), or close the file but not using try-finally or the \"with\"

6条回答
  •  终归单人心
    2020-11-22 01:06

    Although it is quite safe to use such construct in this particular case, there are some caveats for generalising such practice:

    • run can potentially run out of file descriptors, although unlikely, imagine hunting a bug like that
    • you may not be able to delete said file on some systems, e.g. win32
    • if you run anything other than CPython, you don't know when file is closed for you
    • if you open the file in write or read-write mode, you don't know when data is flushed

提交回复
热议问题