Skip to content
Advertisement

Subtract 2 hex files line by line in python

Have 2 files with hex values

file1.txt

0x42528566923Bd44c
0x55A5c6564546b54d
0x3266CD6565e566aa

file2.txt

0x3256AA323ab
0x669bbbb544c
0xa2545bcca55

using python i am trying to subtract line 1 of file1.txt from line 1 of file2.txt and so on. My codes

with open("file1.txt", "r") as f1:
    line1 = f1.readline().strip()

          
def key1(line1):
    x = int(line1, 16)
    return (x)
      
      

with open("file2.txt", "r") as f2:
    line2 = f2.readline().strip()

    
def key2(line2):
    y = int(line2, 16)
    return (y)
    
def add(f1, f2):
    P = key1(line1)
    Q = key2(line2)
    R = P - Q
    hx = hex(R).zfill(10)
    print(hx+"n")
    

add(f1, f2) 

but I am only able to get first line subtract value, not getting all 3 lines value.

Advertisement

Answer

The problem is with: line1 = f1.readline().strip() and line2 = f2.readline().strip(). Since you are reading the first line only from each files, you have a single result. You need to do it for all the lines, not just the first one.

Read all the lines, and strip each of them:

with open("file1.txt", "r") as f1:
    line1 = [line.strip() for line in f1.readlines()]
with open("file2.txt", "r") as f2:
    line2 = [line.strip() for line in f2.readlines()]

Now, modify the add function signature:

def add(line1, line2):
    P = key1(line1)
    Q = key2(line2)
    R = P - Q
    hx = hex(R).zfill(10)
    print(hx+"n")

The key1 and key2 functions are fine, so they don’t need to be modified.

Now, call add for each pair of lines from the files, iterating them parallely with zip:

for i,j in zip(line1, line2):
    add(i, j)

OUTPUT:

0x425282412798b0a1
0x55a5bfec898b6101
0x3266c34020289c55
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement