Is explicitly closing files important?

前端 未结 6 771
野的像风
野的像风 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

    Some Pythons will close files automatically when they are no longer referenced, while others will not and it's up to the O/S to close files when the Python interpreter exits.

    Even for the Pythons that will close files for you, the timing is not guaranteed: it could be immediately, or it could be seconds/minutes/hours/days later.

    So, while you may not experience problems with the Python you are using, it is definitely not good practice to leave your files open. In fact, in cpython 3 you will now get warnings that the system had to close files for you if you didn't do it.

    Moral: Clean up after yourself. :)

提交回复
热议问题