我已经看到在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™,我应该使用前者,但我想知道后者有什么后果(如果有的话)?