johnny_b_good
johnny_b_good

Reputation: 41

Difference between two values in txt file, python

I have some values in each line of a txt file. Now I want to calculate the difference between

line[1] - line[0], line[3] - line[2]

and so forth.

import sys

l = []
i = 0
f=open('Isotop1.txt')
# i = Zeilennummer, line = text der Zeile
for line in enumerate(f):
    l.append(line)
    for i in l:
        c = l[i] - l[i-1]
        print c


f.close()

later I want to store the solutions in a new text file. but now I get the list indices must be integers, not tuple error. Can someone help?

this is a small sample from the text file. I want to calculate the differences between 33 and 0, 94 and 61 and so on. Maybe I used a completey wrong approach to this problem...

0
33
61
94
122
153
178
200
227
246
274
297
310
324

Upvotes: 1

Views: 1076

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

with open("in.txt") as f:
    # get first line/number
    nxt = int(next(f))
    for n in f:
        print("absolute difference between {} and {} = {}"
              .format(n.rstrip(), nxt, abs(int(nxt) - int(n))))
        # set nxt equal to the next number
        nxt = int(next(f,0))

Output:

absolute difference between 33 and 0 = 33
absolute difference between 94 and 61 = 33
absolute difference between 153 and 122 = 31
absolute difference between 200 and 178 = 22
absolute difference between 246 and 227 = 19
absolute difference between 297 and 274 = 23
absolute difference between 324 and 310 = 14

If you want to use each number:

def diff(fle):
    with open(fle) as f:
        nxt = int(next(f))
        for n in f:
            yield abs(int(nxt) - int(n))
            nxt = int(next(f,0))

print(list(diff("in.txt")))
[33, 33, 31, 22, 19, 23, 14]

Or iterate over and get one number at a time:

for n in diff("words.txt"):
    print(n)

Output:

33
33
31
22
19
23
14

Using 0 as a default value to next will avoid a StopIterationError.

If you are doing a lot of numerical computation numpy might be better:

import numpy as np

arr = np.loadtxt("words.txt", dtype=np.int)

diff = np.abs(np.diff(arr.reshape(-1,2)).flatten())

print(diff)

Upvotes: 2

Related Questions