[Tutor] do I need f.close()

Kent Johnson kent37 at tds.net
Tue Jun 10 19:42:19 CEST 2008


On Tue, Jun 10, 2008 at 1:07 PM, dave selby <dave6502 at googlemail.com> wrote:
> Hi All,
>
> Up to now I when I need to write some data to a file I have been
> purposely using close()
>
> f = open(conf, 'w')
> f.writelines(lines)
> f.close()
>
> Is it as safe to use the following ....
>
> open(conf, 'w').writelines(lines)

I will do this with file *read* in code that is not intended to be
production quality. For writes and production code I always call close
explicitly.
>
> ie no close() to flush the data, but also not assigned an object name
> so am I right in thinking that as the object is 'reclaimed' close() is
> automatically called ?

In the current implementation of CPython I believe that is correct.
For Jython, it is not correct, as Jython uses a different (not
reference counted) GC. Perhaps that is why I am scrupulous about
closing files that I open for write; I'm pretty sure I have been
burned by it and I did a lot of Jython coding a few jobs ago...

Kent


More information about the Tutor mailing list