Try to search your question here, if you can't find : Ask Any Question Now ?

How to continue loop while checking if file exists using function in python

HomeCategory: stackoverflowHow to continue loop while checking if file exists using function in python
Avatarcraig asked 4 months ago

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):
            val = int(val)
            return val
            print('Not a valid integer')

    def checkFile(fileName):
        File = open(fileName)
        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:

            elif val == 1:
                fileName = input('Enter a file name: ')
                inFile = open(fileName,'r') 


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

1 Answers
Best Answer
AvatarAmit answered 4 months ago
Your Answer

2 + 8 =

Popular Tags

WP Facebook Auto Publish Powered By :