file.close()
Bryan
belred1 at yahoo.com
Thu Jul 24 21:48:30 EDT 2003
"Francois Pinard" <pinard at iro.umontreal.ca> wrote in message
news:mailman.1059052897.16526.python-list at python.org...
> [Bryan]
>
> > I'm curious to know how others handle the closing of files. [...] I'm
> > aware that files will automatically be closed when the process exits.
>
> For one, I systematically avoid cluttering my code with unneeded `close'.
> The advantages are simplicity and legibility, both utterly important to
me.
>
> However, I do understand that if I ever have to move a Python script
> to Jython, I will have to revise my scripts for adding the clutter I am
> sparing today. I'm quite accepting to do that revision if this occurs.
> Until then, I prefer keeping my scripts as neat as possible.
>
> For me, explicitely closing a file, for which the only reference is about
> to disappear through function exiting, would be very similar to using
> `del' on any variable I happened to use in that function: gross
overkill...
>
> The only reason to call `close' explicitly is when there is a need to
close
> prematurely. Absolutely no doubt that such needs exist at times. But
> closing all the time "just in case" is symptomatic of unsure programming.
> Or else, it is using Python while still thinking in other languages.
>
> --
> François Pinard http://www.iro.umontreal.ca/~pinard
>
you are correct this is so awesome... at least for me it is... now i remove
a lot of my clutter too :) i just did some tests on windows by trying to
delete file1 at the command prompt when raw_input is called.
f = file('file1')
raw_input('pause')
### the file is NOT closed
file('file1')
raw_input('pause')
### the file IS closed
f = file('file1')
del f
raw_input('pause')
### the file IS closed
def foo():
f = file('file1')
foo()
raw_input('pause')
### the file IS closed
can you explain to me how the file gets closed? i'm sure that garbage
collection hasn't happed at the point that i call raw_input. it must have
something to do with the reference count of the file object. does python
immediately call close for you when the reference count goes to zero? i
want the dirty details...
thanks,
bryan
More information about the Python-list
mailing list