【问题标题】:Trying to use the filenotfound error in python open file function尝试在 python 打开文件函数中使用 filenotfound 错误
【发布时间】:2020-10-15 08:53:47
【问题描述】:

我正在为我的程序的开头创建一个文件打开功能,它会提示用户输入文件名,然后它将打开该文件。我试图为此使用 try-except 函数,以便如果它是有效文件,则打印它,如果它不是有效文件,则返回 filenotfound 错误。我不确定如何实现文件未找到错误。到目前为止,这是我想出的:

def open_file():
   file = input("Please input a file to use: ")
   try:
       fp = open(file)
   except:
       filenotfounderror

我很确定这应该可以工作,但我不确定在 except 之后要写什么来代替 filenotfound 错误

【问题讨论】:

  • 如果文件不能被opened,一个FileNotFound 错误将单独引发......你实际上不需要做任何事情

标签: python python-3.x


【解决方案1】:

应该是这样的:

def open_file():
       file = input("Please input a file to use: ")
       try:
           fp = open(file)
       except FileNotFoundError:
         print("File Not Found")

【讨论】:

    【解决方案2】:

    我认为以下是您正在寻找的内容

     def open_file():
       file_name = input("Please input a file to use: ")
       try:
           fp = open(file_name)
           # do something with the file - dont forget to close it
       except FileNotFoundError:
          print(f"Wrong file or file path: {file_name}")
    

    【讨论】:

      【解决方案3】:

      你不需要 try/except 来做这个;如果找不到文件,Python 将在没有您帮助的情况下引发 FileNotFoundError。

      您的代码会做的是用 FileNotFoundError 替换所有其他错误(权限被拒绝、文件名无效、雷蒙德上空的错误月相等)。不要那样做(通常是don't use a blanket except,至少在你确切知道自己在做什么之前)。

      如果您想引发异常,其关键字是raise。例如;

      try:
          with open(input("File: ")) as inp:
              # ... do something
      except FileNotFoundError as exc:
          print("ooops, we got a", exc)
          raise ValueError("Surreptitiously replacing %s" % exc)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-28
        • 2012-05-01
        • 2020-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多