【问题标题】:How to continue loop while checking if file exists using function in python如何在使用python中的函数检查文件是否存在时继续循环
【发布时间】:2019-03-07 05:48:15
【问题描述】:

我正在尝试创建一个代码,该代码将使用一个函数来检查文件是否存在,如果不存在,它将再次询问用户文件名。这个循环应该继续,直到给出一个现有的文件名。我设法使用一个函数来检查第一个输入是否是整数,但我似乎无法将它复制到文件名部分而不会出现错误(FileNotFoundError:[Errno 2] No such file or directory: ) 并结束循环。 (它仍然打印“无效文件”位,但以错误结尾)

这是我的代码中的一个 sn-p:

    def checkInt(val):
        try:
            val = int(val)
            return val
        except:
            print('Not a valid integer')

    def checkFile(fileName):
      try:
        File = open(fileName)
        File.close
      except:
        print('Not a valid file.')


    def main():
        print('Hi welcome to the file processor')
        while 1:
            val = checkInt(input('''Selection Menu:
    0. Exit program
    1. Read from a file
    '''))

            if val == 0:
              print('goodbye')
              quit()

            elif val == 1:
                fileName = input('Enter a file name: ')
                checkFile(fileName)
                inFile = open(fileName,'r') 
                print(inFile.read())
                inFile.close

    main()

我觉得这是一个明显的错误,我非常感谢你的洞察力!

【问题讨论】:

    标签: python file file-not-found


    【解决方案1】:

    您可以在循环中添加exception FileNotFoundError:continue

    def checkInt(val):
        try:
            val = int(val)
            return val
        except:
            print('Not a valid integer')
    
    def main():
        print('Hi welcome to the file processor')
        while 1:
            val = checkInt(input('''Selection Menu:
       0. Exit program
       1. Read from a file
       '''))
    
        if val == 0:
            print('goodbye')
            exit()    
        elif val == 1:
            fileName = input('Enter a file name: ')
            checkInt()
            inFile = open(fileName, 'r')
            print(inFile.read())
            inFile.close 
    

    输出

    Hi welcome to the file processor
    Selection Menu:
       0. Exit program
       1. Read from a file
       1
    Enter a file name: blahblah
    Not a valid file.
    Selection Menu:
       0. Exit program
       1. Read from a file
       1
    Enter a file name: hey.txt
    5,7,11,13,17,19,23,29,31,37,41,43,47,
    Selection Menu:
       0. Exit program
       1. Read from a file
    

    编辑

    您可以在checkFile 方法中执行相同的操作,只需调用您的main()

    def checkFile(fileName):
        try:
            File = open(fileName)
            File.close
        except FileNotFoundError:
            print('Not a valid file.')
            main()
    

    【讨论】:

    • 是的,我知道我可以做到这一点,但我正在做的练习表明它必须通过一个函数来完成,这就是我挣扎的原因。不过感谢您的帮助!我可能会像你建议的那样在循环中实现一个“继续”,然后就结束了。
    • @bebarrentine 太好了,如果有帮助,您可以接受答案:meta.stackexchange.com/questions/5234/…
    • 刚刚做了,非常感谢!我能够让它工作
    【解决方案2】:
    import os
    
    def checkFile():
        file_name = input("Enter File name: ")
        while(os.path.isfile(file_name )==False):
            print("Not a valid file")
            file_name = input("Enter File name: ")
        return True # if the function is expecting a boolen, else return the filename to open it
    

    【讨论】:

      猜你喜欢
      • 2015-02-21
      • 2019-01-31
      • 1970-01-01
      • 2019-06-24
      • 2021-01-10
      • 2012-02-27
      • 2011-12-22
      • 1970-01-01
      • 2018-06-21
      相关资源
      最近更新 更多