Gregory Lee - 1 year ago 65
Python Question

# Python - Sum of List with multiple rows

I am trying to solve this problem where I have to add up the list with multiple lines. But I was unable to find a solution.

Code:

``````g = input("Enter the file name:")
infile = open(g,'r')

counter = 0
for lu in infile:
lu = lu.strip()
lulu = lu.split(",")
lulu = [float(i) for i in lulu]

coo = sum(lulu)

print("The sum of your numbers is " + str(coo) + ".")
``````

Current Output:

``````Enter the file name:nums.txt
[-2.5, 2.0]
[8.0]
[100.0, 3.0, 5.1, 3.7]
[6.5]
The sum of your numbers is 6.5.
``````

Expected Output:

``````Enter the file name:nums.txt
[-2.5, 2.0]
[8.0]
[100.0, 3.0, 5.1, 3.7]
[6.5]
The sum of your numbers is 125.8.
``````

Since you are overwriting `lulu` with each line, at the end it is only printing the sum of the last line.

Try the following:

``````g = input("Enter the file name:")
infile = open(g,'r').read().splitlines() #make infile a list of each line in the file

lulu = [float(j) for i in infile for j in i.split(',')] #split each line by a comma, and append each item, (converted to a float) to the list lulu

coo = sum(lulu)

print("The sum of your numbers is " + str(coo) + ".")
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download