CPython automatically closes the file object when the object is deleted; it is deleted when the reference count drops to zero (no variables access it). Therefore, if you use mergeData in a function, as soon as the function is executed, the local variables will be cleared and the file will be closed.
If you use allData = open( "myinput.txt","r" ).read() , the reference count drops to 0 when .read() returns, and on CPython it means that the file is closed there and then.
In other implementations, such as Jython or IronPython, where the lifetime of an object is controlled differently, the time it takes to delete the object may be much later.
The best way to use the file is as a context manager:
with open( "myinput.txt","r" ) as mergeData: allData = mergeData.read()
which automatically calls .close() on mergeData . See the documentation for file.open() and the documentation for the with statement.
Martijn Pieters Feb 26 '13 at 21:11 2013-02-26 21:11
source share