Reputation: 1499
I am in need of some help doing some simple calculations in a for loop. I have two columns in the below example file. Column 1 is the date-time-hr-min-ss and column 2 is a value. I would like to print through the file and calculate the difference between the current value and the value of the previous hour. I attempted the code below but not able to subtract the previous hour value. Can I get some help/direction in correcting my code below? Thanks in advance.
File Contents:
20160823220000 1208091708
20160823230000 1209559863
20160824000000 1210706089
20160824010000 1211612458
20160824020000 1212410614
20160824030000 1213059346
My Code:
with open('datecount.txt') as data:
z = 0
for line in data:
x = (line.strip().split())
num = int(x[1])
z = num
print(z - z)
Desired Output:
date-time-hr-min-ss Value Delta-from-prev-Hr
==========================================================
20160823220000 1208091708 N/A
20160823230000 1209559863 1468155
20160824000000 1210706089 1146226
20160824010000 1211612458 906369
20160824020000 1212410614 798156
20160824030000 1213059346 648732
Upvotes: 0
Views: 2898
Reputation: 848
Well if you can assume that each consecutive line in your file will be the hour following the previous hour, you don't need to even worry about messing with the time column. Just use this..
with open('datecount.txt') as data:
z = 0
for line in data:
x = (line.strip().split())
num = int(x[1])
print(num - z)
z = num
Your code was pretty much doing this already, you just needed to print (num - z) before assigning z to num. And also you had print(z-z) not print(num - z)
Upvotes: 1
Reputation: 3155
with open('datecount.txt') as data:
prev = 0
for line in data:
value = int(line.strip().split()[1])
print(value - prev)
prev = value
It is a good idea to name the variables so that their names make sense. In other words, leave x, y, z
in maths.
Upvotes: 3