0

I am supposed to read from two files. One contains numbers (with invalid characters mixed in) and the other operators. The program stops after an exception is reached but I need it to continue to read the numbers file. I have tried the pass keyword with no luck.

try:
    with open('numbers.txt') as file1, open('operators.txt') as file2:
        for no1, no2, op in itertools.zip_longest(file1, file1, file2):
            result = eval(no1.rstrip() + op.rstrip() + no2.rstrip())
            print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' = ' + str(result))
except IOError:
    print('File cannot be found or opened')
    exit()
except ZeroDivisionError:
    print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' - Division by 0 is not allowed')
except NameError:
    print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' - Cannot perform operation with characters')

I would really appreciate any help.

Sam Quinn
  • 23
  • 3
  • Please add the specific error you are encountering with this code. – alpha1554 Jul 24 '20 at 12:10
  • Does this answer your question? [python catch exception and continue try block](https://stackoverflow.com/questions/19522990/python-catch-exception-and-continue-try-block) – Gamopo Jul 24 '20 at 12:11

2 Answers2

0

You can add continue or pass statement to the except block. Throw the exceptions inside the loop and add continue or pass statement . Check this Answer for reference.

segfault404
  • 281
  • 1
  • 11
0

Split the try-except block & move the ignorable errors to inside the for-loop:

import itertools

try:
    with open('numbers.txt') as file1, open('operators.txt') as file2:
        for no1, no2, op in itertools.zip_longest(file1, file1, file2):
            try:
                result = eval(no1.rstrip() + op.rstrip() + no2.rstrip())
                print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' = ' + str(result))
            except ZeroDivisionError:
                print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' - Division by 0 is not allowed')
            except NameError:
                print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' - Cannot perform operation with characters')
except IOError:
    print('File cannot be found or opened')
    exit()
rdas
  • 20,604
  • 6
  • 33
  • 46