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
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)