简体   繁体   中英

How to find sum of numbers from a file using a while loop?

I am trying to write a function that takes a file name as an argument, and returns the sum of the numbers in the file. Here is what I have done so far:

def sum_digits (filename):
    """
    >>> sum_digits("digits.txt")
    434
    """
    myfile = open(filename, "r")
    newfile = myfile.read()
    sum = 0
    while newfile.isdigit():
        sum += newfile%10
        newfile = newfile/10
    return sum

if __name__=="__main__":
    import doctest
    doctest.testmod(verbose=True)

But this code is not working. I dont know how to do this. Any ideas?

You need to split your text to get a list of numbers, then iterate over that adding them up:

nums = newfile.split()
for num in nums:
    sum += int(num)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM