Open python and memory leaks

When is the file closed?

# Read all data from input file mergeData = open( "myinput.txt","r" ) allData = mergeData.read() mergeData.close() 

Can this code be replaced?

 allData = read.open( "myinput.txt","r" ) 

I was wondering when the file will be closed? would be closed when the statement is executed? or wait until the program exits.

0
python file-io
Feb 26 '13 at 21:10
source share
2 answers

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.

+4
Feb 26 '13 at 21:11
source share

Yes. Yes you can. There is no memory leak or something like that.

The file descriptor will be closed shortly after the file object returned by open() exits the scope and collects the garbage.

Although, if you prefer, you can do something like:

 with open('myinput.txt') as f: data = f.read() 

This ensures that the file is closed as soon as you are done with it.

+2
Feb 26 '13 at 21:12
source share



All Articles