Reading All Numbers In File And Calculate Their Total In Python
I am trying to count all numbers in given file. It works unless there is a word between a numbers. e.g: 1 2 car 3 4 Here's my code: def main(): count=0 with open('numbers.txt', '
Solution 1:
You should move the try
and except
blocks inside your loop. Then when you hit a line with a non-number, you'll just skip it and go on the the next line.
Unrelated to that error, you can also simplify your code a bit by iterating over the file directly in a for
loop, rather than calling readline
repeatedly in a while
loop:
withopen("numbers.txt", "r") as f:
for line in f: # simpler loopprint(line.strip())
try: # move this inside the loop
count += int(line)
except Exception as err: # you may only want to catch ValueErrors hereprint(err)
print(count)
Solution 2:
you can use isdigit
to check for number:
while line != '':
print(line.strip())
if line.strip().isdigit():
count += int(line.strip())
line = f.readline()
Here is Pythonic way to achieve this if you want to sum all digit:
f = open('file')
total_count = sum(int(x) for x in f if x.strip().isdigit())
if you want to count how many of them are digit:
f = open('file')
total_digit = len(x for x in f if x.strip().isdigit())
Solution 3:
You can use the isdigit
method to check if the line contains only numbers:
def main():
count=0
with open("numbers.txt", "r") as f:
count = sum(int(line) for line in f if line.strip().isdigit())
print(count)
if __name__ == '__main__':
main()
Solution 4:
You can try using regular expressions:
import re
total = 0withopen("numbers.txt", "r") as f:
line = f.readline()
while line != '':
total += sum([int(x) for x in re.findall('(\\d+)', line)])
line = f.readline()
print total
Post a Comment for "Reading All Numbers In File And Calculate Their Total In Python"