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

2024-04-25 09:37:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个代码,它将使用一个函数来检查文件是否存在,如果不存在,它将再次要求用户输入文件名。在给定现有文件名之前,此循环应该继续。我试着用一个函数来检查第一个输入是否是整数,但我似乎无法在没有得到错误(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()

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


Tags: 文件函数代码文件名def错误notval
1条回答
网友
1楼 · 发布于 2024-04-25 09:37:42

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

输出

^{pr2}$

编辑

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

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

相关问题 更多 >

    热门问题