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
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.