NameError: name 'variable_name" is not defined when i try to catch an execption

NameError: name 'variable_name" is not defined when i try to catch an execption

您好,我正在尝试创建一个程序来读取两个 txt.files 并在控制台上为用户显示它们。

我想为至少一个文件不在同一目录中的情况编写一个例外。

我现在显示的代码适用于两个文件都在目录中的情况。 但是,当我尝试测试我的异常时,我得到 NameError =“list_of_cats”未找到的回溯错误,然后显示我的自定义消息。

我应该如何编写程序才能显示我的 custom_message。

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)

这是错误信息:

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

错误发生是因为打印时变量list_of_catslist_of_dogs在打印时没有定义。要解决此问题,您可以使用以下代码:

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)