[Tutor] Need to explicitly del a file object after reading contents?

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Jun 25 14:27:55 EDT 2004

> Is it necessary to do this:
> f = open(filepath,'r')
> filestring = f.read()
> f.close()
> del f
> vs. this?
> filestring = open(filepath,'r').read()


The second is fine if you only want to suck the file into memory 
and do nothing else. If you want to read bits at a time, or 
read it multiple times (rewinding to the begining with seek() 
in between) then the first method is better. But even then you 
don't need the del line, after you close the file the file 
variable will be swept away in the garbage.


Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list