[Tutor] Re: Re: Translating to Python [perl --> python]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 2 Jul 2002 09:27:44 -0700 (PDT)


On Tue, 2 Jul 2002, Kyle Babich wrote:

> It works!  :)  Thank you.

Very cool!


> My next question is how do I open a file for appending vs. overwritting?
> I don't see this in any tutorials.  (or maybe I'm just missing it)

For this, you'll want to tell open() to read your file in "append" mode.
So something like:

###
>>> f = open('helloworld.txt', 'w')
>>> f.write("hello!")
>>> f.close
<built-in method close of file object at 0x8151640>
>>> f.close()
>>> f = open('helloworld.txt', 'a')
>>> f.write(' world!')
>>> f.close()
>>> f = open('helloworld.txt', 'r')
>>> content = f.read()
>>> print content
hello! world!
###



By the way, notice what happens when I forget to use parentheses in the
f.close:

###
>>> f.close
<built-in method close of file object at 0x8151640>
###

That's because, even if a function doesn't take any arguments, it doesn't
"fire off" until parentheses are used.  What this statement is doing,
instead, is giving us the function itself as an object.  The closest
analogy to Perl would be taking a reference to a subroutine object.


For more information about open(), you can take a look at:

    http://www.python.org/doc/lib/built-in-funcs.html#built-in-funcs


Best of wishes!