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

pan@uchicago.edu pan@uchicago.edu
Wed Apr 23 15:05:02 2003

> 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.

Try this:


f1=open('c:/py/digest/f1.txt', 'r')
f2=open('c:/py/digest/f2.txt', 'r')
f3=open('c:/py/digest/f3.txt', 'w')

a= [x.strip() for x in f1.readlines()] # a = ['1','3','4']
b= [x.strip() for x in f2.readlines()] # b = ['1','2','3','4','5']

c= [(((x in a) and (x+'*\n')) or (x+'\n')) for x in b]



The main part is:

[(((x in a) and (x+'*\n')) or (x+'\n')) for x in b]

in which (((x in a) and (x+'*\n')) or (x+'\n')) is equivilant to:

       if x in a:
        return x + '*\n'
        return x + '\n'

if let it be f(x), then it becomes:

c= [f(x) for x in b]


 The example I show here doesn't take the following situation into

f1: 1,3,4,6     <==== 
f2: 1,2,3,4,5

'6' is not in f2, so it is not included in the f3. 

Since this situation is not described in your question, so I will
just leave it this way.