It is good practice to use the with keyword when dealing with file
objects. The advantage is that the file is properly closed after its
suite finishes, even if an exception is raised at some point. Using
with is also much shorter than writing equivalent try-finally blocks:
If you’re not using the with keyword, then you should call f.close()
to close the file and immediately free up any system resources used by
it.
If you don’t explicitly close a file, Python’s garbage collector
will eventually destroy the object and close the open file for you,
but the file may stay open for a while. Another risk is that different
Python implementations will do this clean-up at different times.
使用
它不仅涉及自动关闭,而且还涉及异常情况下的正确关闭。你知道吗
Doku:methods of file objects
如果你用这个:
然后你不必关闭你的文件,它是自动完成的。在使用完文件后关闭它们总是一个好的做法(减少内存泄漏的风险,等等…)
文件将在退出或垃圾回收期间自动关闭。但作为最佳实践,更好的方法是使用如下上下文管理器:
谢谢你。你知道吗
相关问题 更多 >
编程相关推荐