The close()
here happens when the file
object is deallocated from memory, as part of its deletion logic. Because modern Pythons on other virtual machines — like Java and .NET — cannot control when an object is deallocated from memory, it is no longer considered good Python to open()
like this without a close()
. The recommendation today is to use a with
statement, which explicitly requests a close()
when the block is exited:
with open('myfile') as f:
# use the file
# when you get back out to this level of code, the file is closed
If you do not need a name f
for the file, then you can omit the as
clause from the statement:
with open('myfile'):
# use the file
# when you get back out to this level of code, the file is closed
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…