Authors: | Tom Dunham |
---|---|
Date: | 2009-03-24 |
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
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
So how do you put the character \ into a string?
>>> escape = "\\" >>> escape '\\' >>> print escape \
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) |
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'
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()
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
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
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 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.
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.
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.
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: ...
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.
>>> fsock = open("notthere", "r") Traceback (innermost last): File "<interactive input>", line 1, in ? IOError: [Errno 2] No such file or directory: 'notthere'
>>> 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
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"
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()
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.
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()
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].