reading files

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Dec 19 06:42:25 EST 2005


On Mon, 19 Dec 2005 02:47:22 -0800, Johhny wrote:

> Thanks for your assistance, Is it proper practice in python to flush
> any memory when you exit? for example Ive read the file into memory,
> when I close the file do I also have to flush any memory allocations ?

You've done this:

fileobject = file("my file", "r")
mytext = fileobject.read()
fileobject.close()

(It is good practice to close the file as soon as you can, especially on
platforms like Windows where open files can't be read by any other process.)

The text you read is still hanging around, waiting for you to use it. Once
you are done with it, you might want to reclaim that memory used,
especially if it is a 100MB text file:

mytext = ""  # re-bind the name 'mytext' to the empty string

Now that enormous chunk of text will be collected by the Python garbage
collector, reclaiming the memory used.

But even that is not always needed: if the name 'mytext' is local to a
function, then when the function ends, the block of memory used will be
collected by the Python garbage collector, and you don't have to do a
thing. 


-- 
Steven.




More information about the Python-list mailing list