user3782831
user3782831

Reputation: 45

Read numbers from a file and return sum of all the numbers

I want to get sum of all the numbers which are separated by commas in a python file suppose (example.txt): which contain the numbers like,

2,3,5,6,9
1,5,6,9,4,5
9,5

Upvotes: 0

Views: 408

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339340

The standard way of reading files in python is to use open() and then either read() or readlines(). See e.g. here.

To get the numbers out, you need to split the read lines by the separator and convert them into an int.

Finally sum() will sum up all elements in a list.

#create an empty list to put numbers in
a = []

#open file and read the lines
with open("SO_sumofnumers.txt", "r") as f:
    lines = f.readlines()


for line in lines:
    #split each line by the separator (",")
    l = line.split(",")
    for entry in l:
        # append each entry
        # removing line-end ("\n") where necessary
        a.append(int(entry.split("\n")[0]))

print a
#sum the elements of a list
s = sum(a)
print s

Upvotes: 1

Related Questions