Wednesday, February 2, 2022

Code to handle file not found

import sys

try:

    with open('journal.txt', 'a') as f:

        f.write('input')

except IOError as exc:    # Python 2. For Python 3 use OSError

    tb = sys.exc_info()[-1]

    lineno = tb.tb_lineno

    filename = tb.tb_frame.f_code.co_filename

    print('{} at {} line {}.'.format(exc.strerror, filename, lineno))

    sys.exit(exc.errno)