Why no open(f, "w").write()?

Delaney, Timothy tdelaney at avaya.com
Thu May 30 00:54:39 EDT 2002


> From: VanL [mailto:news at lindbergs.org]
> 
> Ok, I've read the thread... but how is
> 
> open(f, 'w').write(stuff)
> 
> different than
> 
> lines = open(f).readlines()
> 
> in terms of bad/good programming practice?
> 
> I use that second construction quite frequently.

It suffers from the same problems, but the symptoms aren't as bad.

With the read version, the file may still hang around without being closed.
This may prevent other processes (or the same process) from opening the
file. Usually when the program exists the OS will close the file.

With the write version, the file may hang around without being closed or
flushed. Thus when the program exits, the file may be closed without being
flushed, and thus may not contain the data that you thought you wrote to it.

Tim Delaney





More information about the Python-list mailing list