Have 2 files with hex values
file1.txt
JavaScript
x
4
1
0x42528566923Bd44c
2
0x55A5c6564546b54d
3
0x3266CD6565e566aa
4
file2.txt
JavaScript
1
4
1
0x3256AA323ab
2
0x669bbbb544c
3
0xa2545bcca55
4
using python i am trying to subtract line 1 of file1.txt from line 1 of file2.txt and so on. My codes
JavaScript
1
28
28
1
with open("file1.txt", "r") as f1:
2
line1 = f1.readline().strip()
3
4
5
def key1(line1):
6
x = int(line1, 16)
7
return (x)
8
9
10
11
with open("file2.txt", "r") as f2:
12
line2 = f2.readline().strip()
13
14
15
def key2(line2):
16
y = int(line2, 16)
17
return (y)
18
19
def add(f1, f2):
20
P = key1(line1)
21
Q = key2(line2)
22
R = P - Q
23
hx = hex(R).zfill(10)
24
print(hx+"n")
25
26
27
add(f1, f2)
28
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:
JavaScript
1
5
1
with open("file1.txt", "r") as f1:
2
line1 = [line.strip() for line in f1.readlines()]
3
with open("file2.txt", "r") as f2:
4
line2 = [line.strip() for line in f2.readlines()]
5
Now, modify the add
function signature:
JavaScript
1
7
1
def add(line1, line2):
2
P = key1(line1)
3
Q = key2(line2)
4
R = P - Q
5
hx = hex(R).zfill(10)
6
print(hx+"n")
7
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
:
JavaScript
1
3
1
for i,j in zip(line1, line2):
2
add(i, j)
3
OUTPUT:
JavaScript
1
4
1
0x425282412798b0a1
2
0x55a5bfec898b6101
3
0x3266c34020289c55
4