【问题标题】:Exception Error Handling in python spits out error after specifying not topython中的异常错误处理在指定不后吐出错误
【发布时间】:2019-07-30 20:46:22
【问题描述】:

我试图阻止这段代码给我一个关于我创建的名为 lovely.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)

【问题讨论】:

  • 你得到的输出和错误是什么?
  • 并添加错误的完整回溯,以便我们(和您)可以看到哪一行引发了错误。

标签: python python-3.x python-2.7 error-handling filenotfoundexception


【解决方案1】:

一些提示:

  • 除了class 名称之外,不要大写变量。
  • 在引用不同的事物时使用不同的变量名。 (即不要使用Filenames = open("beloved.txt", mode="rb"),当您已经拥有该变量的全局版本,该变量的本地版本,现在您将其重新分配为又是一次不同的事情!!这种行为会让人头疼...

脚本的主要问题是试图在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 是什么?在所有情况下,您都会得到相同的结果...

【讨论】:

  • 所以这些建议奏效了,我只是让自己感到困惑,因为我在全局和本地引用该文件,这意味着错误代码将多次发布。我确实删除了返回数据部分,因为它重复。感谢 Reedinationer
  • @abdullahalhamidi 没问题!很高兴为您提供帮助 :) 如果这解决了您的问题,您应该单击我的帖子旁边的复选标记以将线程标记为已解决。
【解决方案2】:

“with open(Filenames) as fill_objec:”语句会抛出异常。 因此,您至少必须将该句子包含在 try 部分中。在您的代码中,您首先以文字形式获取该 len,然后检查特定文件 lovely.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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 2019-02-05
    相关资源
    最近更新 更多