How to sum all the numbers in a text file?

前端 未结 3 1870
误落风尘
误落风尘 2020-12-22 02:03

I have to calculate the sum of any numbers in the file and print the sum.

A number is defined as any string beginning with a digit 0 through 9 followed by any numbe

3条回答
  •  忘掉有多难
    2020-12-22 03:09

    def function():
    
        infile = open("test.txt", 'r')
        content = infile.read()       
        infile.close()
        wordList = content.split()
    
        total = 0
    
        for i in wordList:
            if i.isnumeric():
                total += int(i)
        return total
    

    In this solution, I named the file test.txt. The idea is you loop through wordList which is a list containing every item spliced in test.txt (try printing wordList before the loop to see for yourself). We then try to cast each item as a int (this assumes no decimals will be in the file, if so you can include a float cast). We then catch ValueError which gets raised when casting i.e 'a' as an int.

提交回复
热议问题