[Tutor] Reading & printing lines from two different files

Jeff Shannon jeff@ccvcorp.com
Thu, 06 Jun 2002 11:48:15 -0700


stuart_clemons@us.ibm.com wrote:

> Hi all:
>
> I have two files, file1 and file2. I want to print the first line
> from file1, then the first line from file2, then the second line
> from file 1, then the second line from file 2, etc.

What do you want to do if one file is shorter than the other?

The basic method I would use would probably go something like this --

import sys

file1 = open('file1', 'r')
file2 = open('file2', 'r')

while 1:
    line1 = file1.readline()
    sys.stdout.write(line1)
    line2 = file2.readline()
    sys.stdout.write(line2)
    if not line1 and not line2:
        break

This will print interleaved lines until one file is exhausted, print
the remaining lines from the other file, and then break.  You can
alter this behavior by adjusting the conditions for the break
statement.  For example, 'if not line1 or not line2' would cause
printing to stop as soon as either file is exhausted.

You're probably wondering what that sys.stdout.write() stuff is.  I
used that instead of print, because print will add newlines (and
sometimes spaces).  Often this is useful, but since you're reading
lines from a file, they already have a newline at the end of them.  I
*could* strip that newline off before printing, but there's another
problem.  When one file is exhausted (we've reached EOF on it),
readline() will return an empty string, and printing that empty string
will output an extra space.  I could test for an empty line, too
(either before or after stripping the newline), but it's easier to use
sys.stdout.write(), which sends an exact string to the standard
output, without doing any of the "helpful" formatting that print
does.  This way, I use the newlines from the file without needing to
fiddle with them, and write()ing an empty string does nothing --
exactly what I want.

Hope this helps...

Jeff Shannon
Technician/Programmer
Credit International