首页 > 解决方案 > Different ways of closing files in Python

问题描述

Usually it is required to call the .close() method on a file object or use the "with open" construct to make sure it gets closed.

However, I am wondering if writing to a file like this leaves the file closed:

open(path,'w').writelines(fileContents)

标签: python

解决方案


No, open(path,'w').writelines(fileContents) does not close the file. It's left in an open state, even though the file object is anonymous and it's not assigned to anything. CPython will clean up the handle if it goes out of scope.

Furthermore, I believe garbage collection would have to occur, which may or may not happen at the end of a block (it usually does, but there's no mandate or guarantee AFAIK). Other Python interpreters may or may not close the file when it goes out of scope, so don't rely on that mechanism for general Python code.

It's best to just use the with idiom and be done with it. There are very few reasons not to use with when dealing with file descriptors.


推荐阅读