如何使用python中的函数检查文件是否存在时继续循环

问题描述 投票:-2回答:1

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

这是我代码中的代码段:

    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个回答
0
投票

你可以在循环中添加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 

OUTPUT:

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()
© www.soinside.com 2019 - 2024. All rights reserved.