Home » Python » python – Exception Handling Problem with OSError [Errno 22]-Exceptionshub

python – Exception Handling Problem with OSError [Errno 22]-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

The 3.7 documentation states that we should handle OSError exceptions as such:

except OSError as err:
    print("OS error: {0}".format(err))

I still get an error with program exit when I do exactly that. The error is:

   File "F:/working/workfile.py", line 55, in main
    OutFile = open(FileName, 'w')
OSError: [Errno 22] Invalid argument: 'bad<>file.txt'

Full, relevant area of code:

def main():
        InvalidInput = True

        while InvalidInput:
                #Start Exception handling
                try:
                        # Ask user for how many random numbers to create
                        NumberCount = int(input('How many numbers do you want to generate?'))

                        # Ask the user where the created numbers are to be stored
                        # Error out if invalid characters are used
                        FileName = input('Where do you want the files to be written to?')

                # Catch the error if invalid characters are used

                except OSError as err:
                        print("OS error: {0}".format(err))
                        print ('Please enter a valid path/filename.')
                        InvalidInput = True

                except IOError:
                        print ('Please enter a valid path/filename.')
                        InvalidInput = True

                except ValueError:
                        print ('Invalid number.  Please enter only integers')
                        InvalidInput = True

                else:
                        InvalidInput = False
                        OutFile = open(FileName, 'w')
                        for Number in range (NumberCount):
                                # Call the function(s) for generating random numbers
                                # and writing to the output file
                                ReturnNumber = RandomNumbers.RandomWriter ()
                                OutFile.write (str(ReturnNumber))
                                OutFile.write ("\n")

                                print ('Writing ', ReturnNumber)

                        # Close the file when finished
                        OutFile.close()

        print ('Closing the open file.')

main()

Typing a filename with valid characters works just fine. I need the program to not crash out, and hand this exception. Any advice on what I’m missing?

Thanks

How to&Answers:

The code that deals with opening and reading from the file should be within the try block of the try/except statement like so:

try:
    # ... preceding code...

    OutFile = open(FileName, 'w')
    for Number in range (NumberCount):
        # Call the function(s) for generating random numbers
        # and writing to the output file
        ReturnNumber = RandomNumbers.RandomWriter ()
        OutFile.write (str(ReturnNumber))
        OutFile.write ("\n")

        print ('Writing ', ReturnNumber)

    # Close the file when finished
    OutFile.close()
except: