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.
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.
c = 200
if a != 0:
c = 200 / a
c = 200
try:
c = 200 / a
except ZeroDivisionError:
pass
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.
try:
# Something dangerous
except IndexError:
# Handle the error
else:
# No problems so do something
finally:
# Clean up either way
You can handle multiple types of exceptions in one except block.
try:
# Something dangerous
except (TypeError, IndexError):
# Handle either type
You can also define multiple except cases to handle different exception types in different ways.
try:
# Something dangerous
except TypeError:
# Handle type error
except IndexError:
# Handle index error
except:
# Handle all other types
try:
# Something dangerous
except TypeError as e:
print e
print e.args
# Handle type error
Some common exception classes:
For a full list see http://docs.python.org/library/exceptions.html
Creating exceptions is as easy as creating a class.
class EveryonePanicException(Exception):
pass
As with any class you can also pass additional information into your exceptions.
class EveryonePanicException(Exception):
def __init__(self, reason):
self.reason
def __str__(self):
return 'Everyone panic! %s' % self.reason
The raise keyword is used to raise the specified exception.
raise EveryonePanicException("It's Godzilla!")
If you’ve caught an exception that you don’t intend to handle then you can re-raise the last exception with raise.
try:
raise EveryonePanicException("It's Godzilla!")
except EveryonePanicException:
print "There was an exception."
raise
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.
try:
import json
except ImportError:
import simplejson as json
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).
open_file = open('example.txt')
contents = open_file.readlines() # Reads entire file
open_file.close()
You can avoid having to remember to close the file by opening the file using a with statement:
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.
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.
class Example(object):
def __enter__(self):
print "Calling Enter"
return 73
def __exit__(self, exc_type, exc_value, traceback):
print "Calling Exit: %s, %s, %s" % (
exc_type, exc_value, traceback
)
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.
with open('example.txt') as f:
for line in f:
print line
with open(__file__) as f:
print u''.join(f.readlines())
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.
with open('example.txt', 'w') as f:
f.write('Line 1\n')
f.writelines(['Line 2\n', 'Line 3\n'])
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')
The os module has helper functions for working with file paths. Some handy functions are
You can also get the relative file using the module’s __file__ attribute.
import os
print __file__
print os.getcwd()
print os.path.abspath(__file__)
print os.path.abspath(os.path.join(os.getcwd(), '..', 'test'))
print os.path.splitext('test.txt')
The os module also has helper functions for working with directories.
import os
root = os.getcwd()
for item in os.listdir(root):
print item
def visit(arg, dirname, names):
print arg, dirname, names
os.path.walk(root, visit, None)
CSV
Functional programming in Python