python 中的异常错误处理在指定不执行后吐出错误

Exception Error Handling in python spits out error after specifying not to

我试图阻止这段代码给我一个关于我创建的名为 beloved.txt 的文件的错误我使用 FillNotFoundError: 说不要给我错误并打印找不到的文件而是打印消息和错误消息。我该如何解决?

def count_words(Filenames):
    with open(Filenames) as fill_object:
        contentInFill = fill_object.read()

    words = contentInFill.rsplit()
    word_length = len(words)
    print("The file " + Filename + " has " + str(word_length) + " words.")

    try:
        Filenames = open("beloved.txt", mode="rb")
        data = Filenames.read()
        return data
    except FileNotFoundError as err:
        print("Cant find the file name")

Filenames = ["anna.txt", "gatsby.txt", "don_quixote.txt", "beloved.txt", "mockingbird.txt"]
for Filename in Filenames:
    count_words(Filename)

几点提示:

  • 不要将 class 名称以外的变量大写。
  • 引用不同的事物时使用不同的变量名。 (即,当您已经拥有该变量的全局版本时,不要使用 Filenames = open("beloved.txt", mode="rb")and 是该变量的本地版本,and 现在您又将其重新指定为不同的意思 !! 这种行为会导致头痛...

脚本的主要问题是试图在 try 语句之外打开文件。您可以将代码移动到 try: 内!当你不使用 err 时,我也不明白 except FileNotFoundError as err:。在这种情况下,您应该将其重写为 except FileNotFoundError: :)

def count_words(file):
    try:
        with open(file) as fill_object:
            contentInFill = fill_object.read()
        words = contentInFill.rsplit()
        word_length = len(words)
        print("The file " + file + " has " + str(word_length) + " words.")
        with open("beloved.txt", mode="rb") as other_file:
            data = other_file.read()
        return data
    except FileNotFoundError:
        print("Cant find the file name")

filenames = ["anna.txt", "gatsby.txt", "don_quixote.txt", "beloved.txt", "mockingbird.txt"]
for filename in filenames:
    count_words(filename)

我也不明白为什么当从同一个文件读取数据时你有你的函数 return data 而不管你输入到函数的 file?在所有情况下您都会得到相同的结果...

"with open(Filenames) as fill_objec:" 语句会抛出异常。 所以你至少必须把那句话放在 try 部分。在您的代码中,您首先以单词形式获取该 len,然后检查特定文件 beloved.txt。此双重代码可让您获得重复的 mensajes。建议:

def count_words(Filenames):
    try:
        with open(Filenames) as fill_object:
            contentInFill = fill_object.read()
        words = contentInFill.rsplit()
        word_length = len(words)
        print("The file " + Filename + " has " + str(word_length) + " words.")
    except FileNotFoundError as err:
        print("Cant find the file name")