简体   繁体   中英

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.

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])
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. Eg the import line should be pushed to left-most.

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)

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)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM