newbie newbie - 3 months ago 12
Python Question

python: how to count number in one file?

I need to write a Python program to read the values in a file, one per line, such as file: test.txt

1
2
3
4
5
6
7
8
9
10


Denoting these as j1, j2, j3, ... jn,
I need to sum the differences of consecutive values:

a=(j2-j1)+(j3-j2)+...+(jn-j[n-1])


I have example source code

a=0
for(j=2;j<=n;j++){
a=a+(j-(j-1))
}
print a


and the output is

9

Answer

If I understand correctly, the following equation;

a = (j2-j1) + (j3-j2) + ... + (jn-(jn-1))

As you iterate over the file, it will subtract the value in the previous line from the value in the current line and then add all those differences.

a = 0

with open("test.txt", "r") as f:
    previous = next(f).strip()
    for line in f:
        line = line.strip()
        if not line: continue
        a = a + (int(line) - int(previous))
        previous = line

print(a)