[Tutor] Comparing lines in two files, writing result into a third file

stuart_clemons@us.ibm.com stuart_clemons@us.ibm.com
Wed Apr 23 07:43:02 2003





Hi all:

I have two files, file1.txt and file 2. txt, each containing numbers.  I
want to compare the numbers in the files and put an asterisk at the end of
the numbers that match, writing the result into a third file, .  Hopefully
the following illustrates what I'm trying to do:

File1.txt
1
3
4

File2.txt
1
2
3
4
5

The result after my slick Python program:

File3.txt
1 *
2
3 *
4 *
5

I've tried various combinations of opening the files and 'if' nests, but I
can't seem to get it right.  Any hints on what structure to use.  Thanks in
advance.




----- Forwarded by Stuart Clemons/Westford/IBM on 04/23/03 07:30 AM -----
                                                                                                                                       
                      Stuart Clemons                                                                                                   
                                               To:       tutor@python.org                                                              
                      06/06/02 01:57 PM        cc:                                                                                     
                                               Subject:  Reading & printing lines from two different files                             
                                                                                                                                       



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