【问题标题】:Python try-except-exceptPython try-except-except
【发布时间】:2019-06-26 21:44:20
【问题描述】:

我将包含此代码应该执行的任务的描述,以防有人需要它来回答我。

#Write a function called "load_file" that accepts one 
#parameter: a filename. The function should open the
#file and return the contents.#
#
# - If the contents of the file can be interpreted as
#   an integer, return the contents as an integer.
# - Otherwise, if the contents of the file can be
#   interpreted as a float, return the contents as a
#   float.
# - Otherwise, return the contents of the file as a
#   string.
#
#You may assume that the file has only one line.
#
#Hints:
#
# - Don't forget to close the file when you're done!
# - Remember, anything you read from a file is
#   initially interpreted as a string.


#Write your function here!
def load_file(filename):
    file=open(filename, "r")
    try:
        return int(file.readline())
    except ValueError:
        return float(file.readline())
    except:
        return str(file.readline())
    finally:
        file.close()


#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print 123, followed by <class 'int'>.
contents = load_file("LoadFromFileInput.txt")
print(contents)
print(type(contents))

当使用包含“123”的文件测试代码时,一切正常。当网站加载另一个文件来测试这段代码时,会出现以下错误:

[Executed at: Sat Feb 2 7:02:54 PST 2019]

    We found a few things wrong with your code. The first one is shown below, and the rest can be found in full_results.txt in the dropdown in the top left:

    We tested your code with filename = "AutomatedTest-uwixoW.txt". We expected load_file to return the float -97.88285. However, it instead encountered the following error:

    ValueError: could not convert string to float:

所以我猜测错误发生在第一个 except 语句中,但我不明白为什么。如果将文件中的值转换为浮点数时发生错误,代码不应该转到第二个except 语句吗?而在第二个except 中,它将被转换为字符串,这仍然可以工作吗?我猜我误解了try-except(specified error)-except(no specified error) 的工作原理。

抱歉,帖子太长了。

【问题讨论】:

  • 另外,如果错误发生在 try: 块中,则该行已被读取,并且下次调用 readline() 时,它将读取文件中的下一行,因此您的 @987654330 @ 代码不会在与失败的值相同的值上运行,而是在文件中的下一个值上运行。也许将读取的行放在 var 中,并在 tryexcept 块中返回 var 的转换。
  • 这是下一个发生的问题,用你的建议解决了。谢谢。

标签: python try-except


【解决方案1】:

代码不应该直接转到第二个 except 语句吗?

不:这个“扁平”的 try/except 语句仅适用于 first try 块。如果那里发生异常,except 分支会捕获此异常并立即评估相应的块。如果这个块发生异常,它不会被任何东西捕获,因为那里没有try块。

因此,您必须执行大量嵌套的 try/except 语句:

try:
    do_this()
except ValueError:
    try:
        do_that()
    except ValueError:
        do_this()
    except:
        do_that_one()
except:
    # a whole bunch of try/except here as well

您可能需要添加额外的嵌套级别。

就您需要编写的代码量而言,这非常低效。更好的选择可能是:

data = file.readline()
for converter in (int, float, str):
    try:
        return converter(data)
    except:
        pass

请注意,如果您执行converter(file.readline()),则每次迭代都会读取一个新行(或者,在您的情况下,在任何新的 try/except 块中),这可能不是您需要的。

【讨论】:

    【解决方案2】:

    不,只有一个 except 块——第一个匹配异常的块——将被执行。您所描述的行为将对应于

    except ValueError:
        try:
            return float(file.readline())
        except:
            return str(file.readline())
    

    【讨论】:

      【解决方案3】:
      def load_file(filename):
          file=open(filename, "r")
          try:
              val = file.readline()
              return int(val)
          except ValueError:
              try:
                  return float(val)
              except:
                  return str(val)
          finally:
              file.close()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-19
        • 2011-04-25
        • 1970-01-01
        • 2017-05-14
        • 1970-01-01
        • 2020-12-11
        • 2013-04-10
        相关资源
        最近更新 更多