Files & Exceptions

Authors: Tom Dunham
Date: 2009-03-24

String Escapes

The answer is using escape sequences

>>> "he said \"hello\" they said"
'he said "hello" they said'

See: http://docs.python.org/reference/lexical_analysis.html#string-literals

For a complete list of escape sequences

Whitespace

Characters that don't really print are called whitespace characters.

>>> "he\tsaid hello"
'he\tsaid hello'
>>> print "he\tsaid hello"
he      said hello
>>>
>>> print "\n".join("he said hello".split(" "))
he
said
hello

String Escapes (2)

So how do you put the character \ into a string?

>>> escape = "\\"
>>> escape
'\\'
>>> print escape
\

String Escapes: Reference

Escape Sequence Meaning
newline Ignored
\ Backslash ()
' Single quote (')
" Double quote (")
a ASCII Bell (BEL)
f ASCII Formfeed (FF)
n ASCII Linefeed (LF)
r ASCII Carriage Return (CR)

Files

Escaping the directory separators is important on Windows, or you will not be able to find the file

>>> f = open("barcoding\\barcodingdata.txt", "rb")
>>> f
<open file 'barcoding\\barcodingdata.txt', mode 'rb' at 010E3988>
>>> f.mode
'rb'
>>> f.name
'barcoding\\barcodingdata.txt'

Reading Files

Read the whole file with read

>>> f = open("barcoding\\barcodingdata.txt")
>>> f
<open file 'barcoding\barcodingdata.txt', mode 'r' at 0x00E2AE78>
>>> data = f.read()
>>> len(data)
878970
>>> f.close()

Reading chunks

If you have a large file it is often more efficient to read and process it in chunks.

Often, you will want to read every line in a file

for line in open("barcoding\\barcodingdata.txt"):
    print line

Breaking a loop

If you are processing a large file, you may find what you are interested in quickly and want to stop processing. You can jump out of a loop using break:

for line in open("barcoding\\barcodingdata.txt"):
    if len(line) > 100:
        break
    print line

Exercise

See handout

Write a hangman game. The computer picks a word at random, and the player attempts to guess the word by guessing letters.

You can use the choice function from the random module to choose a random item from a list. There is a wordlist called crosswd.txt which you can load.

You can use this function to draw the gallows:

def print_gallows(wrongs):
    """
    Print the gallows picture for the game hangman.

    wrongs is the number of incorrect guesses the player has made.
    """
    gallows = """
 _________
|         |
|         0
|        /|\\
|        / \\
|
|""".lstrip().splitlines()

    print "\n".join(gallows[0:wrongs+1])

Exceptions

Exceptions often indicate an error.

>>> d = {"server":"mpilgrim", "database":"master"}
>>> d["mpilgrim"]
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
KeyError: mpilgrim

What we don't know is what exceptions are, or why they are useful.

The Stack

To understand exceptions, you need to know a bit about the way functions work. To call a function, Python does the following

So, when you enter a function something must keep track of where you came from. This is called the stack.

Raising

When a program encounters an error condition, it must signal this to the interpreter. It does this by raising an exception.

The exception travels through (unwinds) the stack, at each point looking for a handler, a block of code that has been written to deal with this kind of problem.

Handling

The handler is part of your function, it sits around a block of code and if any exceptions that it knows how to deal with are raised, it catches them and stops the stack unwinding.

The handler can then deal with the exception, or re-raise it.

try:
   ...
except Error:
   ...

Unhandled Exceptions

If there is no handler for the kind of exception that was raised, it reaches the top level, where Python deals with it as best it can.

If you are running interactively, Python prints some error messages and carries on. If not, the whole program stops (with an error message). This is called an unhandeled exception.

Exceptions: Opening a Non-Existent File

>>> fsock = open("notthere", "r")
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'notthere'

Handling Exceptions

>>> try:
...     fsock = open("/notthere")
... except IOError:
...     print "The file does not exist, exiting gracefully"
... print "This line will always print"

Output

The file does not exist, exiting gracefully
This line will always print

Inspecting the exception

The exception is an object, and so can be inspected (or printed) like all objects:

>>> try:
...     fsock = open("/notthere")
... except IOError, err:
...     print err, "exiting gracefully"
... print "This line will always print"

Writing to a file

Open the file for writing:

>>> outf = open("foo.out", "w")
>>> outf
<open file 'foo.out', mode 'w' at 0x01118650>
>>> outf.write("hello world")
>>> outf.close()

Closing files

A file object (as returned by open) is a new kind of object - it refers to an external resource.

Files are a resource that belongs to the operating system. When you open them, you gain a way to manipulate the file, it's important to show you are finished with them by calling close.

If your script finishes, Python closes all external resources for you.

Finally

Use try...finally to always close a file:

outf = open("foo.out", "w")
try:
    outf.write(...)
    # something goes wrong here
    # and an exception is thrown
finally:
    # this is always executed
    outf.close()

Exercise

See handout

Write a script called head.py that will print the first 10 lines of a file (passed in as a parameter). Handle nonexistent files with an error message.

You can pass arguments into a program on the command line. These are available as a list called argv in the module sys. The first argument is the name of the script you are running, so you will want sys.argv[1].