0

Firstly, here is my code ::

def tryfirst():
    try:
        f = open('testfile.txt')
    except FirstNotFound as e:
        trysecond()
    else:
        print(f.read())
        f.close()

def trysecond():
    try:
        f = open('test_file.txt')
    except StillNotFound as e:
        print(e)
    else:
        print(f.read())
        f.close()

tryfirst()

What am I trying to accomplish?

I would like my program to try to open a text file that doesn't exist (testfile.txt), and after it tries that one, if it fails it moves onto the next one that does exist (test_file.txt) and prints the contents of the file. I want it to initiate the program by calling the first function, tryfirst, as done at the bottom of the code.

When I try to run this, I get the following and not sure why ::

NameError: global name 'FirstNotFound' is not defined
5
  • FirstNotFound What is this? IOError? Did you define those exceptions previously by subclassing the exception class? Feb 12, 2017 at 3:36
  • 1
    If that is what you would expect to get when the system attempts to open a file that doesn't exist, then yes.
    – Michael
    Feb 12, 2017 at 3:38
  • That's beyond my current level of Python knowledge thus far, unfortunately.
    – Michael
    Feb 12, 2017 at 3:38
  • Uh, what do you expect? You haven't defined those exceptions so that's why you are getting a NameError. Also, open wouldn't throw them anyway... Have you tried to see what exception is actually thrown when you try to open a file that doesn't exist? Feb 12, 2017 at 3:38
  • Just replace FirstNotFound/StillNotFound with IOError Feb 12, 2017 at 3:41

3 Answers 3

1

You just can't name your exceptions anything. Exception docs from python as great source of info. In your case replace FirstNotFound and StillNotFound with IOError

1

you dont have anything named FirstNotFound what you are looking for is IOError

0

This works for me :-

def readFile():
    try:
        f = open('testfile1.txt')
        print(f.read())
        f.close()

    except OSEroor as e:
        f = open('testfile2.text')
        print(f.read())
        f.close()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.