1

Hello I am trying to create a program that reads two txt.files and displays them for the user on the console.

I want to write an exception for the case that atleast one of the files is not in the same directory.

The code I display now works fine for the case that both files are in the directory. However when i try to test my exception i get Traceback Error with NameError ="list_of_cats" not found and then my custom message is displayed.

How should i write the program so that just my custom_message is displayed.

filename_1 = "cats.txt"
filename_2 = "dogs.txt"

try:
    with open(filename_1) as file_object_1, open(filename_2) as file_object_2:
        list_of_cats = file_object_1.read()
        list_of_dogs = file_object_2.read()

except FileNotFoundError:
    print(f"Sorry one of the files {filename_2} is not in this directory")

print(list_of_cats)
print(list_of_dogs)

That's the error message:

NameError: name 'list_of_cats' is not defined
Sorry one of the files dogs.txt is not in this directory

Process finished with exit code 1

1 Answers1

1

The error occurs because when printing the variables list_of_cats and list_of_dogs are not defined while printing them. To fix this you can use the following code:

filename_1 = "cats.txt"
filename_2 = "dogs.txt"

try:
    with open(filename_1) as file_object_1, open(filename_2) as file_object_2:
        list_of_cats = file_object_1.read()
        list_of_dogs = file_object_2.read()

except FileNotFoundError:
    print(f"Sorry one of the files {filename_2} is not in this directory")

else:
    print(list_of_cats)
    print(list_of_dogs)
abhigyanj
  • 2,355
  • 2
  • 9
  • 29
  • thank you, your solution worked :) I get the traceback error because the variables are not in the global scope of the program? – bernd_singer_TL Oct 27 '20 at 06:28
  • The main point is that `list_of_cats` is only defined if you do `list_of_cats = file_object_1.read()`. If the program throws an exception before it reaches this part of the code then there is no `list_of_cats` (not even the name) and that's why you get the `NameError`. – Matthias Oct 27 '20 at 07:54