In Python (>2.7) does the code :
open(\'tick.001\', \'w\').write(\'test\')
has the same result as :
ftest = open(\'tick.
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