[Tutor] Closing file objects when object is garbage collected?

bob gailer bgailer at alum.rpi.edu
Tue Feb 12 14:46:10 CET 2008


Wesley Brooks wrote:
> Dear Python Users,
>
> How do I ensure that when an object is deleted by the garbage
> collector that the file objects contained within the object are
> closed, or collected by the garbage collector?
>   
When there are no more references to a file object the file is closed. 
This happens in your case when the containing object is deleted. All of 
this happens before garbage collection.
> I'd like to avoid having to read the whole file object 
To be precise you should say "avoid having to read the whole file". The 
file object is just the interface to the file contents.
> into a string
> and close the file immediately because the files can potentially be
> large, and I'm dealing with many files at a time.
>
>   
-- 
Bob Gailer
919-636-4239 Chapel Hill, NC



More information about the Tutor mailing list