-2

I have 2 text files I wants to compare column 3 and 4 t only if column 1 and 2 is the same in the files .

Text 1 :

12345,67890,4.6,5.7
89736,62828,5.1,4.2
63793,38392,5.4,7.3

Text 2:

12345,67890,4.6,5.7
63793,38392,5.4,7.3

My code :

pre = open ("g.txt","r")
post = open ("g2.utm","r")
line = pre.readlines()
if not line:                                                
   break                                                     
if line.startswith("L"):
    print ("\n")         #to avoid the header
else :    
    v = line[0:5]                                      
    l = line[6:11]                                      
    i = line[12:14]
    k = line[15:17]
line2 = post.readlines()
if not line2:                                                
   break                                                     
if line2.startswith("L"):
    print ("\n")         #to avoid the header
else :    
    v2 = line[0:5]                                      
    l2 = line[6:11]                                      
    i2 = line[12:14]
    k2 = line[15:17]
    if v == v2 and l == l2 :
        d = (i - i2)
        h = (k - k2)
        if d >= 6.25 and h >=6.25:
            print (v2,l2,"not ok")

print ("Done")
ig0774
  • 39,669
  • 3
  • 55
  • 57

1 Answers1

0

Your code is too much repetitive and messy. Let me suggest you some modification in your code. First read the file line by line. How could you do that?

with open("g.txt","r") as f:
    for line in f:
        a_line_of_the_file = line

Next, instead of accessing the values with index, you can split them with commas and save them to a list.

valuelist = a_line_of_the_file.split(',') 
# contains ["12345","67890","4.6","5.7"] at first iteration.

When you have two list from each row of two files, you can always compare them by index like:

if valuelist1[0]== valueList2[0]:
    do_something

Cast the value first if you need another datatype.

You should now solve your problem yourselves. If you still got error, plz inform.

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • For simultaneous access to files, you can see the link http://stackoverflow.com/questions/11295171/read-two-textfile-line-by-line-simultaneously-python – Ahsanul Haque Sep 12 '15 at 10:43