FreddieB1027
FreddieB1027

Reputation: 5

Python-Creating an array from a .csv file and getting the sum of that array

I have a csv file that has numbers in it that I have entered from another python program. My goal is take these numbers and get the sum of these numbers in python. My first thought would be to pull the numbers from the file and create an array. Then sum the array. I can pull the numbers and print them, but I can't sum them up using sum(array).

The csv file is straightforward like this:

    100
    40
    50

I tried this:

    array=[]

    with open('testScores.csv') as fileName:
        for line in fileName:
            array.append(line.rstrip('\n'))

    total=sum(array)

    print(total)

I get the following error:

    Traceback (most recent call last):
    File "G:\test1.py", line 14, in <module>
    total=sum(array)
    TypeError: unsupported operand type(s) for +: 'int' and 'str'

I'm not very familiar with this and I'm unsure how to proceed.

I will ultimately take this sum and divide it by the number of lines in the CSV file to get an average.

Upvotes: 0

Views: 134

Answers (2)

usual me
usual me

Reputation: 8788

If you have numpy installed, you can do

print sum( numpy.loadtxt( 'testScores.csv' ) )

http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html

Upvotes: 0

mdml
mdml

Reputation: 22912

The source of your error is that there is no tostring method for the list array. Instead, what I think you want to do is push an integer value onto the end of array so that you can sum the array later on.

Assuming that each line contains only one integer value, you can use this:

array.append(int(line))

in place of the 4th line in your code.

Upvotes: 1

Related Questions