python - 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)
解决方案
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.
推荐阅读
- python-2.7 - “未找到 ID”的错误
- html - CSS & SASS 导航问题
- google-cloud-platform - 您可以使用 Cloud Dataflow 检测对象/文件名吗
- prometheus - 大型 WAL 文件
- javascript - javascript代码从执行中跳过了一些行
- mysql - MysqlDump 命令在 cron 中不起作用
- json - XSLT XML 到 JSON 和转义双引号
- python - 如何找到包含熊猫中另一列的所有可能值的行值
- java - 在现有项目结构上设置 gradle
- c# - 在 UserControl 中按下 CTRL+N 键聚焦到 AutoCompleteBox