-2

I'm trying to create a code that will use a function to check if the file exists and if not then it will ask the user for a file name again. This loop should continue until an existing file name is given. I managed to do the same concept using a function to check if the first input was an integer but I can't seem to replicate it for the file name portion without getting an error(FileNotFoundError: [Errno 2] No such file or directory:) and ending the loop. (it still prints the "not valid file" bit but it ends in an error)

Here's a snippet from my code:

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

I feel like its an obvious mistake and I greatly appreciate the insight!

bebarrentine
  • 13
  • 1
  • 4

2 Answers2

0

You may add the exception FileNotFoundError: and continue within the loop:

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

EDIT:

you can do the same within the checkFile method, just call your main():

def checkFile(fileName):
    try:
        File = open(fileName)
        File.close
    except FileNotFoundError:
        print('Not a valid file.')
        main()
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • Yeah I know I can do that, but the exercise I'm doing states it has to be done through a function which is why I'm struggling. Thanks for the help though! I might just implement a 'continue' within the loop like you suggested and call it a day. – bebarrentine Mar 07 '19 at 06:04
  • @bebarrentine Great, you may accept the answer if it helped: https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – DirtyBit Mar 07 '19 at 06:09
  • 1
    Just did, thanks so much! I was able to get it working – bebarrentine Mar 07 '19 at 06:11
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
Harsha pps
  • 2,012
  • 2
  • 25
  • 35