[Tutor] Reading & printing lines from two different files

Andrei Kulakov ak@silmarill.org
Thu, 6 Jun 2002 15:01:39 -0400


On Thu, Jun 06, 2002 at 01:57:02PM -0400, 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.
> 
> Here are my files and what the output should look like:
> 
> File1.txt
> First line file 1
> Second line file 1
> Third line file 1
> 
> File2.txt
> First line file 2
> Second line file 2
> Third line file 3
> 
> This is the output I want when the program is run:
> 
> First line file 1
> First line file 2
> Second line file 1
> Second line file 2
> Third line file 1
> Third line file 2
> 
> I've tried different looping techniques mainly using variations of the
> structure below, but I can't seem to get the output I want.  Any
> suggestions ?  Thanks.
> 
> infile1 = open('c:\file1.txt', 'r')
> infile2 = open ('c:\file2.txt', 'r')
>       for line1 in infile1.readlines():
>             print line1
>       for line2 in infile2.readlines()
>             print line2
>

while 1:
    l = file1.readline()
    if not l: break
    print l
    l = file2.readline()
    if not l: break
    print l

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org