gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:00 24 4
gpt4 key购买 nike

<分区>

我已经看到在 Python 中处理文件的最佳实践是使用 with block :

with open('file', 'r') as fi:
text = fi.read()

with open('file', 'w') as fi:
fi.write(text)

这样,文件会在您完成处理后自动关闭。但我变得懒惰,在快速的一次性脚本中,我倾向于这样做:

text = open('file', 'r').read()
open('file', 'w').write(text)

现在显然,如果我正在编写 Real Software™,我应该使用前者,但我想知道后者有什么后果(如果有的话)?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com