如何使用python

时间:2019-03-07 05:48:16

标签: python file file-not-found

我正在尝试创建一个代码,该代码将使用一个函数来检查文件是否存在,如果不存在,则它将再次询问用户文件名。该循环应继续进行,直到给出现有文件名为止。我设法通过使用函数来检查第一个输入是否为整数来完成相同的概念,但是在没有出现错误的情况下,我似乎无法将其复制为文件名部分(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()

我觉得这是一个明显的错误,对此深表感谢!

2 个答案:

答案 0 :(得分: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 

输出

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()

答案 1 :(得分:0)

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