Reputation: 25
I'm currently learning about "try" and "except" concepts and I have a small question.
def sum_file():
try:
with open("text.txt") as entry:
result = 0
try:
for line in entry:
result += int(line.strip())
print(result)
except ValueError:
print("Non-integer number entered")
except:
print("Non-existent file.")
Each line of the file is a number, some numbers are integers and others are floats. The code correctly sums the first integers but when the first float appears the program stops, when there are more lines further. How do I modify the code for it to continue the operation?
Upvotes: 1
Views: 74
Reputation: 8008
or you can use re to help you.
re.match(r".*\D+.*", line)
match any line which contains one or more not [0-9] character
from io import StringIO
import re
text_txt = """\
3.1
123
4 b 5 6
7.2
c'] ? 9
10
"""
def sum_file():
with StringIO(text_txt) as f:
result_list = []
for line in [_.strip() for _ in f]:
m = re.match(r".*\D+.*", line)
print("Non-integer number entered") if m else (print(line), result_list.append(int(line)))
print(f'result: {sum(result_list)}') if result_list else None
sum_file()
output
Non-integer number entered
123
Non-integer number entered
Non-integer number entered
Non-integer number entered
10
result: 133
Upvotes: 0
Reputation: 15071
You need to put the second try
block inside your loop:
def sum_file():
try:
with open("text.txt") as entry:
result = 0
for line in entry:
try:
result += int(line.strip())
print(result)
except ValueError:
print("Non-integer number entered")
except:
print("Non-existent file.")
Upvotes: 4