Exceptions and File Handling ---------------------------------------- * Understanding Exceptions * Handling Exceptions * Defining Custom Exceptions * Reading/Writing Files * Navigating the File System Understanding Exceptions ---------------------------------------- Things do not always go as planned. If you don't want your program to just crash you'll need to be able to handle exceptions. Same Code but Different Style ---------------------------------------- You have a couple options. In some cases you can do some preliminary checks to make sure that your code will successfully execute. Or you can dive in an catch errors as they happen. Look Before You Leap ---------------------------------------- .. code-block:: python c = 200 if a != 0: c = 200 / a Easier to Ask Forgiveness than Permission ------------------------------------------- .. code-block:: python c = 200 try: c = 200 / a except ZeroDivisionError: pass Catching Exceptions ---------------------------------------- The ``try`` keyword starts the block where exceptions are to be handled. The ``except`` keyword denotes which exception classes are handled. You can also define an ``else`` block which will only excute if no exceptions were raised. A ``finally`` block is also optional and will be excuted regardless of whether there were exceptions or not. Skeleton Example ---------------------------------------- .. code-block:: python try: # Something dangerous except IndexError: # Handle the error else: # No problems so do something finally: # Clean up either way Catching Multiple Types of Exceptions ---------------------------------------- You can handle multiple types of exceptions in one except block. .. code-block:: python try: # Something dangerous except (TypeError, IndexError): # Handle either type Handling Different Exceptions Differently ------------------------------------------ You can also define multiple except cases to handle different exception types in different ways. .. code-block:: python try: # Something dangerous except TypeError: # Handle type error except IndexError: # Handle index error except: # Handle all other types Getting Exception Info ------------------------------------------ .. code-block:: python try: # Something dangerous except TypeError as e: print e print e.args # Handle type error Built-in Exceptions ---------------------------------------- Some common exception classes: - Exception - Base exception class - AttributeError - Attempted to access an object attribute that doesn't exist - IOError - I/O related error (file not found, disk full, etc) - ImportError - Module import error - IndexError - Accessing index outside of list - KeyError - Accessing dictionary key that doesn't exist For a full list see http://docs.python.org/library/exceptions.html Creating Exceptions ---------------------------------------- Creating exceptions is as easy as creating a class. .. code-block:: python class EveryonePanicException(Exception): pass Creating Exceptions Expanded ---------------------------------------- As with any class you can also pass additional information into your exceptions. .. code-block:: python class EveryonePanicException(Exception): def __init__(self, reason): self.reason def __str__(self): return 'Everyone panic! %s' % self.reason Raising Exceptions ---------------------------------------- The ``raise`` keyword is used to raise the specified exception. .. code-block:: python raise EveryonePanicException("It's Godzilla!") Raising Exceptions Again ---------------------------------------- If you've caught an exception that you don't intend to handle then you can re-raise the last exception with ``raise``. .. code-block:: python try: raise EveryonePanicException("It's Godzilla!") except EveryonePanicException: print "There was an exception." raise Supporting Different Python Versions ---------------------------------------- json module was added in Python 2.6 but simplejson is popular third party library. Here we'll check if they have the json module and if not we'll try to use simplejson instead. .. code-block:: python try: import json except ImportError: import simplejson as json Opening Files ---------------------------------------- The built-in ``open`` function is used to open files. It takes the filename, mode (optional), and buffer size (optional). This is implemented as stdio fopen() in the underlying C. The mode defaults to 'r' (for reading). .. code-block:: python open_file = open('example.txt') contents = open_file.readlines() # Reads entire file open_file.close() The File Object ---------------------------------------- Let's take a look at what methods are on the ``File`` type. .. code-block:: python dir(file) Opening File Safely ---------------------------------------- You can avoid having to remember to close the file by opening the file using a with statement: .. code-block:: python with open('example.txt') as f: # do something with f print f.readlines() Note: You must first import ``from __future__ import with_statement`` to use ``with`` in Python 2.5. ``with`` is built-in to Python 2.6 and beyond. With Statement ---------------------------------------- To take a small detour let's talk about the ``with`` statement. The ``with`` statement is used to wrap a code block context manager. The context manager defines an ``__enter__`` to setup the context and ``__exit__`` to clean up the code execution. The common use case is reusing try/except blocks for opening/closing resources. With Example (withexample.py) ---------------------------------------- .. literalinclude:: /code/withexample.py :lines: 1-10 Reading Files ---------------------------------------- The ``file`` objects have a number of methods for reading content. ``readlines`` reads all of the file conents to the EOF character. ``readline`` reads a single line including the new line character. You can also read lines in a file using an interator syntax. .. code-block:: python with open('example.txt') as f: for line in f: print line A Program Which Outputs Itself (output.py) ----------------------------------------------- .. literalinclude:: /code/output.py Writing Files ---------------------------------------- You can write a single string with ``write`` or a list of strings with ``writelines``. Keep in mind that neither method will automatically write new line characters for you. .. code-block:: python with open('example.txt', 'w') as f: f.write('Line 1\n') f.writelines(['Line 2\n', 'Line 3\n']) Appending Files ---------------------------------------- .. code-block:: python with open('example.txt', 'w') as f: f.write('First pass.\n') with open('example.txt', 'a') as f: f.write('This is new.\n') File Paths ---------------------------------------- The ``os`` module has helper functions for working with file paths. Some handy functions are - os.getcwd - os.path.abspath - os.path.dirname - os.path.join - os.path.splitext You can also get the relative file using the module's ``__file__`` attribute. File Paths Example (filepath.py) ---------------------------------------- .. literalinclude:: /code/filepath.py Directories ---------------------------------------- The ``os`` module also has helper functions for working with directories. - os.listdir - os.path.walk - os.mkdir - os.makedirs - os.remove - os.rmdir - os.removedirs Iterating over Directories (directory.py) ------------------------------------------ .. literalinclude:: /code/directory.py Modules Special File Types ---------------------------------------- - XML - DOM (Document Object Model): ``xml.dom`` - SAX (Simple API for XML): ``xml.sax`` - CSV Up Next ---------------------------------------- Functional programming in Python .. header:: MA792K Spring 2011 Lecture 4 .. footer:: © Mark Lavin 2011