0

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

1 Answers1

1

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
Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712