[Tutor] Loading and writing files

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Mon, 31 Jul 2000 14:08:49 -0700 (PDT)


> Next, the file you'll write to should be opened with 'a', instead of 'w',
> as this is repeatedly writing each line, over the line that came before
> it. That's not what you want, I'm guessing.

Since the file is being opened only once, it's probably not necessary to
use append; What append does is check to see if the file exists already
--- if so, then subsequent writes will go at the end of that file.  Append
mode is very useful if you're keeping a log of activity.

In regular writing mode, regardless if the file exists or not, that file's
going to get resized to zero.  Clean slate.  Otherwise, writing to it
subsequentially should be ok.  Here's an annotated interpreter session:

###
# I've written a test file called foo2.txt.  Let's look at it.
>>> file = open('foo2.txt')
>>> print file.read()
I am foo2.txt
This is the end of foo2.txt

# Let's test out append mode:
>>> file = open('foo2.txt', 'a')
>>> file.write("here is another line")
>>> print open('foo2.txt').read()
I am foo2.txt
This is the end of foo2.txt

# Q: Why did this happen?
# A: The file needs to be flushed properly --- I need to close()
#    it.  Whoops.

>>> file.close()
>>> print open('foo2.txt').read()
I am foo2.txt
This is the end of foo2.txthere is another line

# A little bit of strangeness, but only because the file didn't end with
# a newline  ('\n').  The append just tacks onto the end of the file.

# Let's test out regular writing
file = open('foo2.txt', 'w')
file.close()
>>> print open('foo2.txt').read()

# Empty file!  Ok, one more test.
>>> file = open('foo2.txt', 'w')
>>> file.write("testing, testing\n")
>>> file.write("one two three\n")
>>> file.write("testing writing mode\n")
>>> file.close()
>>> print open('foo2.txt').read()
testing, testing
one two three
testing writing mode
###