[Tutor] multiple file output [forgot to close() a file!]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Sep 8 08:47:04 EDT 2003


> > I want to write two strings in two different files. Like i want the
> > user to run the program by specifying the name of the program on
> > command line and want to generate a few files based on the strings of
> > information i have in the code.
>
> Hi Jimmy,
>
> Not a problem --- we'll want to use the 'open()' builtin function again,
> but this time, we want to tell it to open the file in 'write' mode.
> For example:
>
> ###
> f = open('foobar.txt', 'w')
> f.write("Hello world!\n")
> ###

Hi Jimmy,

Yikes, the example wasn't complete --- I neglected to add one essential
line:

###
f = open('foobar.txt', 'w')
f.write('Hello world!\n')
f.close()
###

We need to do close() when we're writing files, because it puts some
finishing touches on the written file.  Many operating systems will
"buffer" its disk writes in large batches for efficiency.  That is, when
we do a close(), we guarantee that the last batch is flushed over to disk.
But if we forget to do this close(), we may lose the lines we've just
written!

I'll try to be more careful next time.


Talk to you later!




More information about the Tutor mailing list