user4932805
user4932805

Reputation:

Adding integers from a file

I'm writing a function that sums up integers from a file.
Here's the code:

def sum_integers_from_file(file_name):
    try:
       file = open(name)
       total = 0
       for i in file:
           total += int(i)
       file.close()
       return total
    except:
       print "error"

file foo.txt:

1234

The function returns 1234.

why doesn't total += int(i) add up all the integers?

Upvotes: 0

Views: 68

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191874

Your file has one line.

You're adding all ints from each line.

If you want to add 1,2,3,4 with that method move them to new lines

Also, you can do the same thing with this

   with open(name) as f:
       return sum(int(line) for line in f)

Upvotes: 2

mrCarnivore
mrCarnivore

Reputation: 5078

It is highly recommended to read files in a with statement. That frees you from the responsibility of closing the file and is also shorter! This works:

def sum_integers_from_file(file_name):
    try:
        with open(file_name, 'r') as f:
            s = f.read()

        total = 0
        for char in s:
            total += int(char)
        return total
    except:
        print("error")

Upvotes: 2

Related Questions