[Tutor] do I need f.close()

Alan Gauld alan.gauld at btinternet.com
Tue Jun 10 19:26:42 CEST 2008

"dave selby" <dave6502 at googlemail.com> wrote 

> 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)

In theory yes, but in practice its much harder to deal with 
if things go wrong. You have no opportunity to catch errors and 
if you do its hard to know whether it was because the file didn't 
open properly or didn't write properly or whatever. Any time you 
are dealing with a lump of metal spinning at high speed, tiny 
distances from a magnet with the potential to hose your data 
its good to be careful...

Most long term programmers have been bitten often enough 
that they use f.close() just to be safe.. :-)

Alan G.

More information about the Tutor mailing list