I am calling function to open text file. In case of exceptions I want to exit the whole program. The code is as follows:
def get_words():
print("File:",FILENAME)
try:
words = open(FILENAME, 'r')
except FileNotFoundError:
print("File {} not found.".format(FILENAME))
sys.exit(1)
except Exception as err:
print("Unexpected Error opening {}".format(FILENAME))
sys.exit(1)
else:
with words:
words2 = words.read()
wordlist = words2.split(" ")
words.close()
return wordlist
pass
I am calling this function in the following code:
words = get_words()
When I execute this, I get error that During Handling of the above exception, another Exception occured
.
Kindly share that why such simple thing is causing error.
Full traceback:
ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.
File: words1.txt
File words1.txt not found.
>Traceback (most recent call last):
File "397635619.py", line 45, in load_words
words = open(FILENAME, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'words1.txt'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3444, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "C:\User\AppData\Local\Temp/ipykernel_8232/397635619.py", line 67, in <module>
wordlist = load_words()
File "C:\Users\AppData\Local\Temp/ipykernel_8232/397635619.py", line 48, in load_words
sys.exit(1)
SystemExit: 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\anaconda3\lib\site-packages\IPython\core\ultratb.py", line 1101, in get_records
return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
File "C:\Users\anaconda3\lib\site-packages\IPython\core\ultratb.py", line 248, in wrapped
return f(*args, **kwargs)
File "C:\Users\anaconda3\lib\site-packages\IPython\core\ultratb.py", line 281, in _fixed_getinnerframes
records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
File "C:\Users\anaconda3\lib\inspect.py", line 1541, in getinnerframes
frameinfo = (tb.tb_frame,) getframeinfo(tb, context)
AttributeError: 'tuple' object has no attribute 'tb_frame'
CodePudding user response:
This should fix the problem.
import sys
import os
def get_words():
print("File:",FILENAME)
if os.path.exists(FILENAME):
with open(FILENAME, 'r') as f:
words2 = f.read()
return words2.split(" ")
else:
print("File {} not found.".format(FILENAME))
sys.exit()
words = get_words()