user9617221
user9617221

Reputation:

Difficulties Iterating over CSV file in Python

I'm trying to add up all the values in a given row in a CSV file with Python but have had a number of difficulties doing so.

Here is the closest I've come:

    from csv import reader
with open("simpleData.csv") as file:
    csv_reader = reader(file)



    for row in csv_reader:
        total = 0
        total = total + int(row[1])
print(total)

Instead of yielding the sum of all the values in row[1], the final print statement is yielding only the last number in the row. What am I doing incorrect?

I've also stumbled with bypassing the header (the next() that I've seen widely used in other examples on SO seem to be from Python 2, and this method no longer plays nice in P3), so I just manually, temporarily changed the header for that column to 0.

Any help would be much appreciated.

Upvotes: 0

Views: 69

Answers (4)

bla
bla

Reputation: 1870

As others have already stated, you are setting the value of total on every iteration. You can move total = 0 outside of the loop or, alternatively, use sum:

from csv import reader

with open("simpleData.csv") as file:
    csv_reader = reader(file)
    total = sum(int(x[0]) for x in csv_reader)

print(total)

Upvotes: 0

Angus
Angus

Reputation: 3728

You are resetting your total, try this:

from csv import reader
with open("simpleData.csv") as file:
    csv_reader = reader(file)

    total = 0

    for row in csv_reader:
        total = total + int(row[1])
print(total)

Upvotes: 0

jjak_82
jjak_82

Reputation: 46

from csv import reader
with open("simpleData.csv") as file:
    csv_reader = reader(file)
    total = 0
    for row in csv_reader:
        total = total + int(row[1])
 print(total)
  1. total should be moved to outside the for loop.
  2. indents are important in Python. E.g. the import line should be pushed to left-most.

Upvotes: 0

nosklo
nosklo

Reputation: 222842

it seems you are resetting the total variable to zero on every iteration.

To fix it, move the variable initialization to outside the for loop, so that it only happens once:

total = 0
for row in csv_reader:
    total = total + int(row[1])

Upvotes: 2

Related Questions