Page 154 -
P. 154

idle session







              Let’s see what happens when you try to open a file that doesn’t exist, such as a disk file called missing.txt.
              Enter the following code at IDLE’s shell:
              >>> try:
                     data = open('missing.txt')
                     print(data.readline(), end='')
              except IOError:
                     print('File error')
              finally:
                     data.close()

                                There’s your error message, but…

              File error
              Traceback (most recent call last):
                File "<pyshell#8>", line 7, in <module>    …what’s this?!? Another exception was
                  data.close()                             raised and it killed your code.
              NameError: name 'data' is not defined



              As the file doesn’t exist, the data file object wasn’t created, which subsequently makes it impossible to call the
              close() method on it, so you end up with a NameError. A quick fix is to add a small test to the finally
              suite to see if the data name exists before you try to call close(). The locals() BIF returns a collection of
              names defined in the current scope. Let’s exploit this BIF to only invoke close() when it is safe to do so:

                                           The “in” operator tests      This is just the bit of code that
              finally:                      for membership.             needs to change. Press Alt-P to
                     if 'data' in locals():                             edit your code at IDLE’s shell.
                             data.close()

              File error
                               No extra exceptions this time.
                               Just your error message.



              Here you’re searching the collection returned by the locals() BIF for the string data. If you find it, you can
              assume the file was opened successfully and safely call the close() method.

              If some other error occurs (perhaps something awful happens when your code calls the print() BIF), your
              exception-handling code catches the error, displays your “File error” message and, finally, closes any opened file.
              But you still are none the wiser as to what actually caused the error.



           118    Chapter 4
   149   150   151   152   153   154   155   156   157   158   159