No need to close file?

Nick Vatamaniuc vatamane at gmail.com
Tue Jul 18 16:17:32 EDT 2006


 I think file object should be closed whether they will be garbage
collected or not. The same goes for DB  and network connections and so
on. Of course in simple short programs they don't have to, but if
someone keeps 1000 open files it might be  better to close them when
done. Besides open files (in 'w' mode) might not be able to be opened
by another process if they are not closed.  In general this is usually
a good habit to have (just like washing dishes right after a meal
rather than hoping someone will do it later eventually ;)

Regards,
Nick V.

Sybren Stuvel wrote:
> T enlightened us with:
> > Do I need to close the file in this case?  Why or why not?
> >
> > for line in file('foo', 'r'):
> >   print line
>
> Nope, it'll get closed automatically when the file object gets garbage
> collected.
>
> Sybren
> --
> The problem with the world is stupidity. Not saying there should be a
> capital punishment for stupidity, but why don't we just take the
> safety labels off of everything and let the problem solve itself?
>                                              Frank Zappa




More information about the Python-list mailing list