By default, the python interpreter, CPython, uses reference counting. This means that when there is no reference to the object, it receives garbage collection, that is, it is cleared.
In your case, doing
open(to_file, 'w').write(indata)
will create an object file for to_file , but will not assign it a name - this means that there is no link to it. You cannot manipulate an object after this line.
CPython will detect this and clear the object after using it. In the case of a file, this means automatic closure. Basically, this is normal and your program will not leak memory.
The "problem" is the implementation mechanism of the CPython interpreter. The language standard does not explicitly guarantee this! If you use an alternative interpreter such as pypy, automatic file closing may be delayed indefinitely. This includes other implicit actions, such as flushing a record when closing.
This problem also applies to other resources, for example. network sockets. It is good practice to always explicitly handle such external resources. Starting with python 2.6, the with statement makes this elegant:
with open(to_file, 'w') as out_file: out_file.write(in_data)
TL; DR: it works, but please do not do this.
MisterMiyagi Mar 16 '16 at 21:16 2016-03-16 21:16
source share