I'm trying to iterate through a list to get a list of outcomes but the first output is incorrect. My code is listed below
with open(csvpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
total = 0
for row in csvreader:
#print(csvreader)
total = int(row[1]) -total
I skipped the first line because it contains the header. I'm essentially supposed to be subtracting (cell B2) 984655 from (cell b1) 867884. But because I'm using a loop, the first value in total
is 867884 or (cell B2 - 0).
Also I cannot use pandas for this problem as stipulated by the instructor.
I've searched the internet and books to find the right way to find the answer with no success.
Results should be (cell B1) 867884 minus (cell b2) 984655. But because I'm using a loop, the first value in total
is 867884 or (cell B2 - 0).
Your line total = int(row[1]) -total
doesn't really make sense because you are only using one column at any point (the row[1] part). It is not the fact you are using a loop, even with your loop you could do something more like:
with open(csvpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
for row in csvreader:
print(int(row[0]) - int(row[1])) # use indexes to specify which column you need
I'll leave it to you to find the best way to only get row B though ;)
I think I got you most of the way there with this code. I stuck a variable 'last' that puts the previous iteration outside of the for loop and assigns it after the loop has run. The problem isn't clean, but hopefully you can take this and solve the problem.
with open('convertcsv.csv', newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
# csv_header = next(csvreader)
cvsfile = csvreader
last = 0
for value in csvreader:
b1 = int(value[1])
b2 = last
if last == 0:
next
total = b1 - b2
print(total)
last = int(value[1])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.