小编Ste*_*one的帖子

不在Python中关闭打开文件会有什么后果?

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

python io file

1
推荐指数
1
解决办法
490
查看次数

标签 统计

file ×1

io ×1

python ×1