Anonymous file closing
Jeff
surferjeff at gmail.com
Fri Jun 11 15:08:47 EDT 2004
Duncan Booth <me at privacy.net> wrote in message news:<Xns9505685D9AE0Cduncanrcpcouk at 127.0.0.1>...
> Sergey Krushinsky <lunarium at comail.ru> wrote in
> news:mailman.845.1086940793.6949.python-list at python.org:
>
> > Hello all,
> >
> > If I need to read a string from a file and use syntax like:
> > text = open(filename, 'r').read()
> > ...
> > is the file object ever closed?
> >
> > With best regards,
> > Sergey
> >
> >
>
> Yes it is closed, but it isn't well defined as to exactly when it is
> closed. You can safely assume that the file will be closed sometime between
> the read returning and your program exiting.
>
> If you aren't worried about portability, and you are using the C
> implementation of Python then you may find it is closed immediately but it
> is poor practice to depend on it.
This is true, but I recommend:
1. Only use the C implementation of Python, a.k.a. The Implementation.
2. Depend on the file being closed immediately in this case. If the
authors of the C implementation ever changed this behavior, they would
break *lots* of existing python code, and they would also break one of
the nicest example of how Python just works.
More information about the Python-list
mailing list