0

I am having some trouble generating the sum of some numbers when reading a file line-by-line. I want to calculate the sum from a separate file without saving the numbers as a list. Is there an easy command for this? My code looks like this:

def imput(filename):
    with open(filename, 'r') as f: #open the file
        for line in f:
            input('sample.txt')`

The file 'sample.txt' consists of the numbers 1,2,4,6,8 and when I use the print function I get:

print(line)

1

2

4

6

8
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Alexander West
  • 81
  • 1
  • 1
  • 9

1 Answers1

1

You can use sum() to total number like:

Code:

total = sum(int(line) for line in open('file1', 'rU'))
print(total)

And if you like the terseness of map() that can be even shorter as:

total = sum(map(int, open('file1', 'rU')))

Results:

21
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135