[Tutor] file io and the open() function

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 20 Nov 2001 02:17:59 -0800 (PST)


On Mon, 19 Nov 2001, Kirk Bailey wrote:

> A novice approaches the masters and asks:
> 
> I want to open a pair of files, read from one, wtite it to another,
> appeding data.

Thus spake the master programmer:

``When you have learned to snatch the error code from the trap frame, it
will be time for you to leave.''

    http://www.canonical.org/~kragen/tao-of-programming.html

*grin*



> I wanted to craft this tool to use variables for the 2 files and the
> domain name, so it would be a useful general purpose tool for use by
> others. Alas, when it tries to open a file with a variable providing
> the namer, it halts and catches fire, barfing evilgrams at me.

Can you show us what sort of brimstone belches from the beast... err...
that is, can you show us an error message?



> Also, as I cannot tell in advance howm any entries will be in the
> source file, this thing has to work in a loop until the source file is
> exausted, then close both files. How do I detet the endoffile and end
> politely, instead of running off the end of the thing and tripping an
> error?

At the very end of a file, readline() will return the empty string
"".  You can use this to your advantage:

###
while 1:
    line = file.readline()
    if not line: break
    ...
###


Alternatively, you can avoid the problem altogether by grabbing your file
as a list of lines, by using readlines():

###
for line in file.readlines():         ## Also look in the docs about
                                      ## xreadlines(), which is better
                                      ## for long files.
   ...
###

For more information about these file methods, you can take a look at:

    http://www.python.org/doc/lib/bltin-file-objects.html


Hope this helps!