我已经看到在Python中使用文件的最佳做法是使用with块:
with open('file', 'r') as fi:
text = fi.read()
with open('file', 'w') as fi:
fi.write(text)
Run Code Online (Sandbox Code Playgroud)
这样,文件在完成后会自动关闭.但是我变得懒惰,而且在快速的一次性脚本中,我倾向于这样做:
text = open('file', 'r').read()
open('file', 'w').write(text)
Run Code Online (Sandbox Code Playgroud)
现在很明显,如果我正在编写Real Software™,我应该使用前者,但我想知道后者有什么后果(如果有的话)?
在CPython上:没有; 当引用计数降为0时,文件将被关闭,这是在.read()和.write()调用返回时立即关闭的.
在其他不使用引用计数的Python实现上,文件将保持打开状态直到收集垃圾.