【问题标题】:Python FileNotFoundError for user input用于用户输入的 Python FileNotFoundError
【发布时间】:2015-03-19 19:59:59
【问题描述】:

我正在制作一个将文件内容加密为密文的程序。我的问题是,当我的程序要求用户输入他们想要加载的文件的名称并且用户没有给出有效的响应时,就会出现“FileNotFoundError:”。我希望我的程序有一个功能,如果用户没有给出有效的响应,程序会不断告诉用户重试。

def EncryptCode():
    encryptFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n") 
    with open (encryptFileLoad,mode="r",encoding="utf=8") as encrypt_file:
        encryptFile = encrypt_file.read()

我收到这样的错误:

Traceback (most recent call last):
    File "C:\...
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

我尝试过这样做:

def EncryptCode():
    ...
    try:
        ...
    except FileNotFoundError:
        return EncryptCode

【问题讨论】:

    标签: python filenotfoundexception file-not-found


    【解决方案1】:

    怎么样

    def EncryptCode():
        file_not_found = True
        while(file_not_found):
            try:
                encryptFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
                file_not_found = False
            except FileNotFoundError:
                print('that didnt work! try again')
        with open (encryptFileLoad,mode="r",encoding="utf=8") as encrypt_file:
            encryptFile = encrypt_file.read()
    

    【讨论】:

      【解决方案2】:

      你几乎成功了。检查http://www.python-course.eu/recursive_functions.php应该是这样的:

      def EncryptCode():
          try:
              encryptFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
              with open(encryptFileLoad,mode="r",encoding="utf=8") as encrypt_file:
                  encryptFile = encrypt_file.read()
                  return encryptFile
          except FileNotFoundError:
              print('File not found. Input correct filename')
              return EncryptCode()
      

      或者您可以使用while 循环来要求用户输入正确的文件名,例如:

      while True:
          try:
              encryptFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
              with open (encryptFileLoad,mode="r",encoding="utf=8") as encrypt_file:
                  encryptFile = encrypt_file.read()
              break
          except FileNotFoundError:
              print('File not found. Input correct filename')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-26
        • 1970-01-01
        • 2021-08-29
        • 2019-04-29
        • 2014-06-17
        • 2020-08-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多