4. More Control Flow Tools

node5.html | tut.html | node7.html | Python Tutorial | node2.html
---
- 4.1 if Statements (node6.html#SECTION006100000000000000000)
  4.2 for Statements (node6.html#SECTION006200000000000000000)
  4.3 The range() Function (node6.html#SECTION006300000000000000000)
  4.4 break and continue Statements, and
  else Clauses on Loops (node6.html#SECTION006400000000000000000)
  4.5 pass Statements (node6.html#SECTION006500000000000000000)
  4.6 Defining Functions (node6.html#SECTION006600000000000000000)
  4.7 More on Defining Functions (node6.html#SECTION006700000000000000000)
  - 4.7.1 Default Argument Values (node6.html#SECTION006710000000000000000)
  4.7.2 Keyword Arguments (node6.html#SECTION006720000000000000000)
  4.7.3 Arbitrary Argument Lists (node6.html#SECTION006730000000000000000)
  4.7.4 Lambda Forms (node6.html#SECTION006740000000000000000)
  4.7.5 Documentation Strings (node6.html#SECTION006750000000000000000)
---
# 4. More Control Flow Tools
Besides the while statement just introduced, Python knows
the usual control flow statements known from other languages, with
some twists.
# 4.1 if Statements
Perhaps the most well-known statement type is the
if statement. For example:
```text

>>> x = int(raw_input("Please enter a number: "))
>>> if x < 0:
... x = 0
... print 'Negative changed to zero'
... elif x == 0:
... print 'Zero'
... elif x == 1:
... print 'Single'
... else:
... print 'More'
...
```
There can be zero or more elif parts, and the
else part is optional. The keyword `elif' is
short for `else if', and is useful to avoid excessive indentation. An
if ... elif ... elif ... sequence
is a substitute for the switch or
case statements found in other languages.
# 4.2 for Statements
The for statement in Python differs a bit from
what you may be used to in C or Pascal. Rather than always
iterating over an arithmetic progression of numbers (like in Pascal),
or giving the user the ability to define both the iteration step and
halting condition (as C), Python's
for statement iterates over the items of any
sequence (e.g., a list or a string), in the order that they appear in
the sequence. For example (no pun intended):
```text

>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
... print x, len(x)
...
cat 3
window 6
defenestrate 12
```
It is not safe to modify the sequence being iterated over in the loop
(this can only happen for mutable sequence types, i.e., lists). If
you need to modify the list you are iterating over, e.g., duplicate
selected items, you must iterate over a copy. The slice notation
makes this particularly convenient:
```text

>>> for x in a[:]: # make a slice copy of the entire list
... if len(x) > 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']
```
# 4.3 The range() Function
If you do need to iterate over a sequence of numbers, the built-in
function range() comes in handy. It generates lists
containing arithmetic progressions, e.g.:
```text

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
The given end point is never part of the generated list;
`range(10)` generates a list of 10 values, exactly the legal
indices for items of a sequence of length 10. It is possible to let
the range start at another number, or to specify a different increment
(even negative; sometimes this is called the `step'):
```text

>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
```
To iterate over the indices of a sequence, combine
range() and len() as follows:
```text

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb
```
# 4.4 break and continue Statements, and
else Clauses on Loops
The break statement, like in C, breaks out of the smallest
enclosing for or while loop.
The continue statement, also borrowed from C, continues
with the next iteration of the loop.
Loop statements may have an `else` clause; it is executed when
the loop terminates through exhaustion of the list (with
for) or when the condition becomes false (with
while), but not when the loop is terminated by a
break statement. This is exemplified by the following loop,
which searches for prime numbers:
```text

>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, 'equals', x, '*', n/x
... break
... else:
... print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
```
# 4.5 pass Statements
The pass statement does nothing.
It can be used when a statement is required syntactically but the
program requires no action.
For example:
```text

>>> while 1:
... pass # Busy-wait for keyboard interrupt
...
```
# 4.6 Defining Functions
We can create a function that writes the Fibonacci series to an
arbitrary boundary:
```text

>>> def fib(n): # write Fibonacci series up to n
... "Print a Fibonacci series up to n"
... a, b = 0, 1
... while b < n:
... print b,
... a, b = b, a+b
...
>>> # Now call the function we just defined:
... fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
```
The keyword def introduces a function definition. It
must be followed by the function name and the parenthesized list of
formal parameters. The statements that form the body of the function
start at the next line, and must be indented. The first statement of
the function body can optionally be a string literal; this string
literal is the function's documentation
string, or docstring.
There are tools which use docstrings to automatically produce online
or printed documentation, or to let the user interactively browse
through code; it's good practice to include docstrings in code that
you write, so try to make a habit of it.
The execution of a function introduces a new symbol table used
for the local variables of the function. More precisely, all variable
assignments in a function store the value in the local symbol table;
whereas variable references first look in the local symbol table, then
in the global symbol table, and then in the table of built-in names.
Thus, global variables cannot be directly assigned a value within a
function (unless named in a global statement), although
they may be referenced.
The actual parameters (arguments) to a function call are introduced in
the local symbol table of the called function when it is called; thus,
arguments are passed using call by value (where the
value is always an object reference, not the value of
the object).4.1 (#foot1251) When a function calls another function, a new local symbol table is
created for that call.
A function definition introduces the function name in the current
symbol table. The value of the function name
has a type that is recognized by the interpreter as a user-defined
function. This value can be assigned to another name which can then
also be used as a function. This serves as a general renaming
mechanism:
```text

>>> fib
<function object at 10042ed0>
>>> f = fib
>>> f(100)
1 1 2 3 5 8 13 21 34 55 89
```
You might object that `fib` is not a function but a procedure. In
Python, like in C, procedures are just functions that don't return a
value. In fact, technically speaking, procedures do return a value,
albeit a rather boring one. This value is called `None` (it's a
built-in name). Writing the value `None` is normally suppressed by
the interpreter if it would be the only value written. You can see it
if you really want to:
```text

>>> print fib(0)
None
```
It is simple to write a function that returns a list of the numbers of
the Fibonacci series, instead of printing it:
```text

>>> def fib2(n): # return Fibonacci series up to n
... "Return a list containing the Fibonacci series up to n"
... result = []
... a, b = 0, 1
... while b < n:
... result.append(b) # see below
... a, b = b, a+b
... return result
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
```
This example, as usual, demonstrates some new Python features:
- The return statement returns with a value from a function.
return without an expression argument is used to return from
the middle of a procedure (falling off the end also returns from a
procedure), in which case the `None` value is returned.
- The statement `result.append(b)` calls a method of the list
object `result`. A method is a function that `belongs' to an
object and is named `obj.methodname`, where `obj` is some
object (this may be an expression), and `methodname` is the name
of a method that is defined by the object's type. Different types
define different methods. Methods of different types may have the
same name without causing ambiguity. (It is possible to define your
own object types and methods, using classes, as discussed later
in this tutorial.)
The method append() shown in the example, is defined for
list objects; it adds a new element at the end of the list. In this
example it is equivalent to "result = result + [b]", but more
efficient.
# 4.7 More on Defining Functions
It is also possible to define functions with a variable number of
arguments. There are three forms, which can be combined.
## 4.7.1 Default Argument Values
The most useful form is to specify a default value for one or more
arguments. This creates a function that can be called with fewer
arguments than it is defined, e.g.
```text

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while 1:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return 1
if ok in ('n', 'no', 'nop', 'nope'): return 0
retries = retries - 1
if retries < 0: raise IOError, 'refusenik user'
print complaint
```
This function can be called either like this:
`ask_ok('Do you really want to quit?')` or like this:
`ask_ok('OK to overwrite the file?', 2)`.
The default values are evaluated at the point of function definition
in the defining scope, so that e.g.
```text

i = 5
def f(arg = i): print arg
i = 6
f()
```
will print `5`.
Important warning: The default value is evaluated only once.
This makes a difference when the default is a mutable object such as a
list or dictionary. For example, the following function accumulates
the arguments passed to it on subsequent calls:
```text

def f(a, l = []):
l.append(a)
return l
print f(1)
print f(2)
print f(3)
```
This will print
```text

[1]
[1, 2]
[1, 2, 3]
```
If you don't want the default to be shared between subsequent calls,
you can write the function like this instead:
```text

def f(a, l = None):
if l is None:
l = []
l.append(a)
return l
```
## 4.7.2 Keyword Arguments
Functions can also be called using
keyword arguments of the form "keyword = value". For
instance, the following function:
```text

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "Volts through it."
print "-- Lovely plumage, the", type
print "-- It's", state, "!"
```
could be called in any of the following ways:
```text

parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')
```
but the following calls would all be invalid:
```text

parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
parrot(110, voltage=220) # duplicate value for argument
parrot(actor='John Cleese') # unknown keyword
```
In general, an argument list must have any positional arguments
followed by any keyword arguments, where the keywords must be chosen
from the formal parameter names. It's not important whether a formal
parameter has a default value or not. No argument may receive a
value more than once -- formal parameter names corresponding to
positional arguments cannot be used as keywords in the same calls.
Here's an example that fails due to this restriction:
```text

>>> def function(a):
... pass
...
>>> function(0, a=0)
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: keyword parameter redefined
```
When a final formal parameter of the form `** name` is
present, it receives a dictionary containing all keyword arguments
whose keyword doesn't correspond to a formal parameter. This may be
combined with a formal parameter of the form
`* name` (described in the next subsection) which receives a
tuple containing the positional arguments beyond the formal parameter
list. (`* name` must occur before `** name`.)
For example, if we define a function like this:
```text

def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, '?'
print "-- I'm sorry, we're all out of", kind
for arg in arguments: print arg
print '-'*40
for kw in keywords.keys(): print kw, ':', keywords[kw]
```
It could be called like this:
```text

cheeseshop('Limburger', "It's very runny, sir.",
"It's really very, VERY runny, sir.",
client='John Cleese',
shopkeeper='Michael Palin',
sketch='Cheese Shop Sketch')
```
and of course it would print:
```text

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
```
## 4.7.3 Arbitrary Argument Lists
Finally, the least frequently used option is to specify that a
function can be called with an arbitrary number of arguments. These
arguments will be wrapped up in a tuple. Before the variable number
of arguments, zero or more normal arguments may occur.
```text

def fprintf(file, format, *args):
file.write(format % args)
```
## 4.7.4 Lambda Forms
By popular demand, a few features commonly found in functional
programming languages and Lisp have been added to Python. With the
lambda keyword, small anonymous functions can be created.
Here's a function that returns the sum of its two arguments:
"lambda a, b: a+b". Lambda forms can be used wherever function
objects are required. They are syntactically restricted to a single
expression. Semantically, they are just syntactic sugar for a normal
function definition. Like nested function definitions, lambda forms
cannot reference variables from the containing scope, but this can be
overcome through the judicious use of default argument values, e.g.
```text

def make_incrementor(n):
return lambda x, incr=n: x+incr
```
## 4.7.5 Documentation Strings
There are emerging conventions about the content and formatting of
documentation strings.
The first line should always be a short, concise summary of the
object's purpose. For brevity, it should not explicitly state the
object's name or type, since these are available by other means
(except if the name happens to be a verb describing a function's
operation). This line should begin with a capital letter and end with
a period.
If there are more lines in the documentation string, the second line
should be blank, visually separating the summary from the rest of the
description. The following lines should be one or more paragraphs
describing the object's calling conventions, its side effects, etc.
The Python parser does not strip indentation from multi-line string
literals in Python, so tools that process documentation have to strip
indentation if desired. This is done using the following convention.
The first non-blank line after the first line of the string
determines the amount of indentation for the entire documentation
string. (We can't use the first line since it is generally adjacent
to the string's opening quotes so its indentation is not apparent in
the string literal.) Whitespace ``equivalent'' to this indentation is
then stripped from the start of all lines of the string. Lines that
are indented less should not occur, but if they occur all their
leading whitespace should be stripped. Equivalence of whitespace
should be tested after expansion of tabs (to 8 spaces, normally).
Here is an example of a multi-line docstring:
```text

>>> def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print my_function.__doc__
Do nothing, but document it.

No, really, it doesn't do anything.
```


5. Data Structures

node6.html | tut.html | node8.html | Python Tutorial | node2.html
---
- 5.1 More on Lists (node7.html#SECTION007100000000000000000)
  - 5.1.1 Using Lists as Stacks (node7.html#SECTION007110000000000000000)
  5.1.2 Using Lists as Queues (node7.html#SECTION007120000000000000000)
  5.1.3 Functional Programming Tools (node7.html#SECTION007130000000000000000)
  5.1.4 List Comprehensions (node7.html#SECTION007140000000000000000)
  5.2 The del statement (node7.html#SECTION007200000000000000000)
  5.3 Tuples and Sequences (node7.html#SECTION007300000000000000000)
  5.4 Dictionaries (node7.html#SECTION007400000000000000000)
  5.5 More on Conditions (node7.html#SECTION007500000000000000000)
  5.6 Comparing Sequences and Other Types (node7.html#SECTION007600000000000000000)
---
# 5. Data Structures
This chapter describes some things you've learned about already in
more detail, and adds some new things as well.
# 5.1 More on Lists
The list data type has some more methods. Here are all of the methods
of list objects:
`append(x)`: Add an item to the end of the list;
equivalent to `a[len(a):] = [x]`.
`extend(L)`: Extend the list by appending all the items in the given list;
equivalent to `a[len(a):] = L`.
`insert(i, x)`: Insert an item at a given position. The first argument is the index of
the element before which to insert, so `a.insert(0, x)` inserts at
the front of the list, and `a.insert(len(a), x)` is equivalent to
`a.append(x)`.
`remove(x)`: Remove the first item from the list whose value is `x`.
It is an error if there is no such item.
`pop( [ i ] )`: Remove the item at the given position in the list, and return it. If
no index is specified, `a.pop()` returns the last item in the
list. The item is also removed from the list.
`index(x)`: Return the index in the list of the first item whose value is `x`.
It is an error if there is no such item.
`count(x)`: Return the number of times `x` appears in the list.
`sort()`: Sort the items of the list, in place.
`reverse()`: Reverse the elements of the list, in place.
An example that uses most of the list methods:
```text

>>> a = [66.6, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.6), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.6, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.6, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.6]
>>> a.sort()
>>> a
[-1, 1, 66.6, 333, 333, 1234.5]
```
## 5.1.1 Using Lists as Stacks
The list methods make it very easy to use a list as a stack, where the
last element added is the first element retrieved (``last-in,
first-out''). To add an item to the top of the stack, use
append(). To retrieve an item from the top of the stack, use
pop() without an explicit index. For example:
```text

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
```
## 5.1.2 Using Lists as Queues
You can also use a list conveniently as a queue, where the first
element added is the first element retrieved (``first-in,
first-out''). To add an item to the back of the queue, use
append(). To retrieve an item from the front of the queue,
use pop() with `0` as the index. For example:
```text

>>> queue = ["Eric", "John", "Michael"]
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.pop(0)
'Eric'
>>> queue.pop(0)
'John'
>>> queue
['Michael', 'Terry', 'Graham']
```
## 5.1.3 Functional Programming Tools
There are three built-in functions that are very useful when used with
lists: filter(), map(), and reduce().
"filter(function, sequence)" returns a sequence (of
the same type, if possible) consisting of those items from the
sequence for which `function ( item )` is true. For
example, to compute some primes:
```text

>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
```
"map(function, sequence)" calls
`function ( item )` for each of the sequence's items and
returns a list of the return values. For example, to compute some
cubes:
```text

>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
```
More than one sequence may be passed; the function must then have as
many arguments as there are sequences and is called with the
corresponding item from each sequence (or `None` if some sequence
is shorter than another). If `None` is passed for the function,
a function returning its argument(s) is substituted.
Combining these two special cases, we see that
"map(None, list1, list2)" is a convenient way of
turning a pair of lists into a list of pairs. For example:
```text

>>> seq = range(8)
>>> def square(x): return x*x
...
>>> map(None, seq, map(square, seq))
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
```
"reduce(func, sequence)" returns a single value
constructed by calling the binary function func on the first two
items of the sequence, then on the result and the next item, and so
on. For example, to compute the sum of the numbers 1 through 10:
```text

>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55
```
If there's only one item in the sequence, its value is returned; if
the sequence is empty, an exception is raised.
A third argument can be passed to indicate the starting value. In this
case the starting value is returned for an empty sequence, and the
function is first applied to the starting value and the first sequence
item, then to the result and the next item, and so on. For example,
```text

>>> def sum(seq):
... def add(x,y): return x+y
... return reduce(add, seq, 0)
...
>>> sum(range(1, 11))
55
>>> sum([])
0
```
## 5.1.4 List Comprehensions
List comprehensions provide a concise way to create lists without resorting
to use of map(), filter() and/or lambda.
The resulting list definition tends often to be clearer than lists built
using those constructs. Each list comprehension consists of an expression
following by a for clause, then zero or more for or
if clauses. The result will be a list resulting from evaluating
the expression in the context of the for and if clauses
which follow it. If the expression would evaluate to a tuple, it must be
parenthesized.
```text

>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> vec = [2, 4, 6]
>>> [3*x for x in vec]
[6, 12, 18]
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]
>>> [{x: x**2} for x in vec]
[{2: 4}, {4: 16}, {6: 36}]
>>> [[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
>>> [x, x**2 for x in vec] # error - parens required for tuples
File "<stdin>", line 1
[x, x**2 for x in vec]
^
SyntaxError: invalid syntax
>>> [(x, x**2) for x in vec]
[(2, 4), (4, 16), (6, 36)]
>>> vec1 = [2, 4, 6]
>>> vec2 = [4, 3, -9]
>>> [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
>>> [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
```
# 5.2 The del statement
There is a way to remove an item from a list given its index instead
of its value: the del statement. This can also be used to
remove slices from a list (which we did earlier by assignment of an
empty list to the slice). For example:
```text

>>> a
[-1, 1, 66.6, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.6, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.6, 1234.5]
```
del can also be used to delete entire variables:
```text

>>> del a
```
Referencing the name `a` hereafter is an error (at least until
another value is assigned to it). We'll find other uses for
del later.
# 5.3 Tuples and Sequences
We saw that lists and strings have many common properties, e.g.,
indexing and slicing operations. They are two examples of
sequence data types. Since Python is an evolving language,
other sequence data types may be added. There is also another
standard sequence data type: the tuple.
A tuple consists of a number of values separated by commas, for
instance:
```text

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
```
As you see, on output tuples are alway enclosed in parentheses, so
that nested tuples are interpreted correctly; they may be input with
or without surrounding parentheses, although often parentheses are
necessary anyway (if the tuple is part of a larger expression).
Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
from a database, etc. Tuples, like strings, are immutable: it is not
possible to assign to the individual items of a tuple (you can
simulate much of the same effect with slicing and concatenation,
though). It is also possible to create tuples which contain mutable
objects, such as lists.
A special problem is the construction of tuples containing 0 or 1
items: the syntax has some extra quirks to accommodate these. Empty
tuples are constructed by an empty pair of parentheses; a tuple with
one item is constructed by following a value with a comma
(it is not sufficient to enclose a single value in parentheses).
Ugly, but effective. For example:
```text

>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
```
The statement `t = 12345, 54321, 'hello!'` is an example of
tuple packing: the values `12345`, `54321` and
`'hello!'` are packed together in a tuple. The reverse operation
is also possible, e.g.:
```text

>>> x, y, z = t
```
This is called, appropriately enough, sequence unpacking.
Sequence unpacking requires that the list of variables on the left
have the same number of elements as the length of the sequence. Note
that multiple assignment is really just a combination of tuple packing
and sequence unpacking!
There is a small bit of asymmetry here: packing multiple values
always creates a tuple, and unpacking works for any sequence.
# 5.4 Dictionaries
Another useful data type built into Python is the dictionary.
Dictionaries are sometimes found in other languages as ``associative
memories'' or ``associative arrays''. Unlike sequences, which are
indexed by a range of numbers, dictionaries are indexed by keys,
which can be any immutable type; strings and numbers can always be
keys. Tuples can be used as keys if they contain only strings,
numbers, or tuples; if a tuple contains any mutable object either
directly or indirectly, it cannot be used as a key. You can't use
lists as keys, since lists can be modified in place using their
append() and extend() methods, as well as slice and
indexed assignments.
It is best to think of a dictionary as an unordered set of
key: value pairs, with the requirement that the keys are unique
(within one dictionary).
A pair of braces creates an empty dictionary: `{}`.
Placing a comma-separated list of key:value pairs within the
braces adds initial key:value pairs to the dictionary; this is also the
way dictionaries are written on output.
The main operations on a dictionary are storing a value with some key
and extracting the value given the key. It is also possible to delete
a key:value pair
with `del`.
If you store using a key that is already in use, the old value
associated with that key is forgotten. It is an error to extract a
value using a non-existent key.
The `keys()` method of a dictionary object returns a list of all
the keys used in the dictionary, in random order (if you want it
sorted, just apply the `sort()` method to the list of keys). To
check whether a single key is in the dictionary, use the
`has_key()` method of the dictionary.
Here is a small example using a dictionary:
```text

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> tel.has_key('guido')
1
```
# 5.5 More on Conditions
The conditions used in `while` and `if` statements above can
contain other operators besides comparisons.
The comparison operators `in` and `not in` check whether a value
occurs (does not occur) in a sequence. The operators `is` and
`is not` compare whether two objects are really the same object; this
only matters for mutable objects like lists. All comparison operators
have the same priority, which is lower than that of all numerical
operators.
Comparisons can be chained: e.g., `a < b == c` tests whether
`a` is less than `b` and moreover `b` equals `c`.
Comparisons may be combined by the Boolean operators `and` and
`or`, and the outcome of a comparison (or of any other Boolean
expression) may be negated with `not`. These all have lower
priorities than comparison operators again; between them, `not` has
the highest priority, and `or` the lowest, so that
`A and not B or C` is equivalent to `(A and (not B)) or C`. Of
course, parentheses can be used to express the desired composition.
The Boolean operators `and` and `or` are so-called
shortcut operators: their arguments are evaluated from left to
right, and evaluation stops as soon as the outcome is determined.
E.g., if `A` and `C` are true but `B` is false, `A
and B and C` does not evaluate the expression C. In general, the
return value of a shortcut operator, when used as a general value and
not as a Boolean, is the last evaluated argument.
It is possible to assign the result of a comparison or other Boolean
expression to a variable. For example,
```text

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
```
Note that in Python, unlike C, assignment cannot occur inside expressions.
C programmers may grumble about this, but it avoids a common class of
problems encountered in C programs: typing `=` in an expression when
`==` was intended.
# 5.6 Comparing Sequences and Other Types
Sequence objects may be compared to other objects with the same
sequence type. The comparison uses lexicographical ordering:
first the first two items are compared, and if they differ this
determines the outcome of the comparison; if they are equal, the next
two items are compared, and so on, until either sequence is exhausted.
If two items to be compared are themselves sequences of the same type,
the lexicographical comparison is carried out recursively. If all
items of two sequences compare equal, the sequences are considered
equal. If one sequence is an initial subsequence of the other, the
shorted sequence is the smaller one. Lexicographical ordering for
strings uses the ASCII ordering for individual characters. Some
examples of comparisons between sequences with the same types:
```text

(1, 2, 3) < (1, 2, 4)
[1, 2, 3] < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4) < (1, 2, 4)
(1, 2) < (1, 2, -1)
(1, 2, 3) == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
```
Note that comparing objects of different types is legal. The outcome
is deterministic but arbitrary: the types are ordered by their name.
Thus, a list is always smaller than a string, a string is always
smaller than a tuple, etc. Mixed numeric types are compared according
to their numeric value, so 0 equals 0.0, etc.5.1 (#foot607)


6. Modules

node7.html | tut.html | node9.html | Python Tutorial | node2.html
---
- 6.1 More on Modules (node8.html#SECTION008100000000000000000)
  - 6.1.1 The Module Search Path (node8.html#SECTION008110000000000000000)
  6.1.2 ``Compiled'' Python files (node8.html#SECTION008120000000000000000)
  6.2 Standard Modules (node8.html#SECTION008200000000000000000)
  6.3 The dir() Function (node8.html#SECTION008300000000000000000)
  6.4 Packages (node8.html#SECTION008400000000000000000)
  - 6.4.1 Importing * From a Package (node8.html#SECTION008410000000000000000)
  6.4.2 Intra-package References (node8.html#SECTION008420000000000000000)
---
# 6. Modules
If you quit from the Python interpreter and enter it again, the
definitions you have made (functions and variables) are lost.
Therefore, if you want to write a somewhat longer program, you are
better off using a text editor to prepare the input for the interpreter
and running it with that file as input instead. This is known as creating a
script. As your program gets longer, you may want to split it
into several files for easier maintenance. You may also want to use a
handy function that you've written in several programs without copying
its definition into each program.
To support this, Python has a way to put definitions in a file and use
them in a script or in an interactive instance of the interpreter.
Such a file is called a module; definitions from a module can be
imported into other modules or into the main module (the
collection of variables that you have access to in a script
executed at the top level
and in calculator mode).
A module is a file containing Python definitions and statements. The
file name is the module name with the suffix .py appended. Within
a module, the module's name (as a string) is available as the value of
the global variable `__name__`. For instance, use your favorite text
editor to create a file called fibo.py in the current directory
with the following contents:
```text

# Fibonacci numbers module

def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b

def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
```
Now enter the Python interpreter and import this module with the
following command:
```text

>>> import fibo
```
This does not enter the names of the functions defined in `fibo`
directly in the current symbol table; it only enters the module name
`fibo` there.
Using the module name you can access the functions:
```text

>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
```
If you intend to use a function often you can assign it to a local name:
```text

>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
```
# 6.1 More on Modules
A module can contain executable statements as well as function
definitions.
These statements are intended to initialize the module.
They are executed only the
first time the module is imported somewhere.6.1 (#foot628)
Each module has its own private symbol table, which is used as the
global symbol table by all functions defined in the module.
Thus, the author of a module can use global variables in the module
without worrying about accidental clashes with a user's global
variables.
On the other hand, if you know what you are doing you can touch a
module's global variables with the same notation used to refer to its
functions,
`modname.itemname`.
Modules can import other modules. It is customary but not required to
place all import statements at the beginning of a module (or
script, for that matter). The imported module names are placed in the
importing module's global symbol table.
There is a variant of the import statement that imports
names from a module directly into the importing module's symbol
table. For example:
```text

>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
```
This does not introduce the module name from which the imports are taken
in the local symbol table (so in the example, `fibo` is not
defined).
There is even a variant to import all names that a module defines:
```text

>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
```
This imports all names except those beginning with an underscore
(`_`).
## 6.1.1 The Module Search Path
When a module named spam is imported, the interpreter searches
for a file named spam.py in the current directory,
and then in the list of directories specified by
the environment variable $PYTHONPATH. This has the same syntax as
the shell variable $PATH, i.e., a list of
directory names. When $PYTHONPATH is not set, or when the file
is not found there, the search continues in an installation-dependent
default path; on Unix, this is usually .:/usr/local/lib/python.
Actually, modules are searched in the list of directories given by the
variable `sys.path` which is initialized from the directory
containing the input script (or the current directory),
$PYTHONPATH and the installation-dependent default. This allows
Python programs that know what they're doing to modify or replace the
module search path. See the section on Standard Modules later.
## 6.1.2 ``Compiled'' Python files
As an important speed-up of the start-up time for short programs that
use a lot of standard modules, if a file called spam.pyc exists
in the directory where spam.py is found, this is assumed to
contain an already-``byte-compiled'' version of the module spam.
The modification time of the version of spam.py used to create
spam.pyc is recorded in spam.pyc, and the
.pyc file is ignored if these don't match.
Normally, you don't need to do anything to create the
spam.pyc file. Whenever spam.py is successfully
compiled, an attempt is made to write the compiled version to
spam.pyc. It is not an error if this attempt fails; if for any
reason the file is not written completely, the resulting
spam.pyc file will be recognized as invalid and thus ignored
later. The contents of the spam.pyc file are platform
independent, so a Python module directory can be shared by machines of
different architectures.
Some tips for experts:
- When the Python interpreter is invoked with the -O flag,
optimized code is generated and stored in .pyo files.
The optimizer currently doesn't help much; it only removes
assert statements and `SET_LINENO` instructions.
When -O is used, all bytecode is optimized;
`.pyc` files are ignored and `.py` files are compiled to
optimized bytecode.
- Passing two -O flags to the Python interpreter
(-OO) will cause the bytecode compiler to perform
optimizations that could in some rare cases result in malfunctioning
programs. Currently only `__doc__` strings are removed from the
bytecode, resulting in more compact .pyo files. Since some
programs may rely on having these available, you should only use this
option if you know what you're doing.
- A program doesn't run any faster when it is read from a .pyc or
.pyo file than when it is read from a .py file; the only
thing that's faster about .pyc or .pyo files is the
speed with which they are loaded.
- When a script is run by giving its name on the command line, the
bytecode for the script is never written to a .pyc or
.pyo file. Thus, the startup time of a script may be reduced
by moving most of its code to a module and having a small bootstrap
script that imports that module. It is also possible to name a
.pyc or .pyo file directly on the command line.
- It is possible to have a file called spam.pyc (or
spam.pyo when -O is used) without a file
spam.py for the same module. This can be used to distribute a
library of Python code in a form that is moderately hard to reverse
engineer.
- The module compileall can create
.pyc files (or .pyo files when -O is used) for
all modules in a directory.
# 6.2 Standard Modules
Python comes with a library of standard modules, described in a separate
document, the Python Library Reference (../lib/lib.html)
(``Library Reference'' hereafter). Some modules are built into the
interpreter; these provide access to operations that are not part of
the core of the language but are nevertheless built in, either for
efficiency or to provide access to operating system primitives such as
system calls. The set of such modules is a configuration option; e.g.,
the amoeba module is only provided on systems that somehow
support Amoeba primitives. One particular module deserves some
attention: sys, which is built into every
Python interpreter. The variables `sys.ps1` and
`sys.ps2` define the strings used as primary and secondary
prompts:
```text

>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print 'Yuck!'
Yuck!
C>
```
These two variables are only defined if the interpreter is in
interactive mode.
The variable `sys.path` is a list of strings that determine the
interpreter's search path for modules. It is initialized to a default
path taken from the environment variable $PYTHONPATH, or from
a built-in default if $PYTHONPATH is not set. You can modify
it using standard list operations, e.g.:
```text

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')
```
# 6.3 The dir() Function
The built-in function dir() is used to find out which names
a module defines. It returns a sorted list of strings:
```text

>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
'stderr', 'stdin', 'stdout', 'version']
```
Without arguments, dir() lists the names you have defined
currently:
```text

>>> a = [1, 2, 3, 4, 5]
>>> import fibo, sys
>>> fib = fibo.fib
>>> dir()
['__name__', 'a', 'fib', 'fibo', 'sys']
```
Note that it lists all types of names: variables, modules, functions, etc.
dir() does not list the names of built-in functions and
variables. If you want a list of those, they are defined in the
standard module __builtin__:
```text

>>> import __builtin__
>>> dir(__builtin__)
['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']
```
# 6.4 Packages
Packages are a way of structuring Python's module namespace
by using ``dotted module names''. For example, the module name
A.B designates a submodule named "B" in a package named
"A". Just like the use of modules saves the authors of different
modules from having to worry about each other's global variable names,
the use of dotted module names saves the authors of multi-module
packages like NumPy or the Python Imaging Library from having to worry
about each other's module names.
Suppose you want to design a collection of modules (a ``package'') for
the uniform handling of sound files and sound data. There are many
different sound file formats (usually recognized by their extension,
e.g. .wav, .aiff, .au), so you may need to create
and maintain a growing collection of modules for the conversion
between the various file formats. There are also many different
operations you might want to perform on sound data (e.g. mixing,
adding echo, applying an equalizer function, creating an artificial
stereo effect), so in addition you will be writing a never-ending
stream of modules to perform these operations. Here's a possible
structure for your package (expressed in terms of a hierarchical
filesystem):
```text

Sound/ Top-level package
__init__.py Initialize the sound package
Formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
Effects/ Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
...
Filters/ Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py
...
```
The __init__.py files are required to make Python treat the
directories as containing packages; this is done to prevent
directories with a common name, such as "string", from
unintentionally hiding valid modules that occur later on the module
search path. In the simplest case, __init__.py can just be an
empty file, but it can also execute initialization code for the
package or set the `__all__` variable, described later.
Users of the package can import individual modules from the
package, for example:
```text

import Sound.Effects.echo
```
This loads the submodule Sound.Effects.echo. It must be referenced
with its full name, e.g.
```text

Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
```
An alternative way of importing the submodule is:
```text

from Sound.Effects import echo
```
This also loads the submodule echo, and makes it available without
its package prefix, so it can be used as follows:
```text

echo.echofilter(input, output, delay=0.7, atten=4)
```
Yet another variation is to import the desired function or variable directly:
```text

from Sound.Effects.echo import echofilter
```
Again, this loads the submodule echo, but this makes its function
echofilter() directly available:
```text

echofilter(input, output, delay=0.7, atten=4)
```
Note that when using `from package import item`, the
item can be either a submodule (or subpackage) of the package, or some
other name defined in the package, like a function, class or
variable. The `import` statement first tests whether the item is
defined in the package; if not, it assumes it is a module and attempts
to load it. If it fails to find it, an
ImportError exception is raised.
Contrarily, when using syntax like `import item.subitem.subsubitem`, each item except for the last must be
a package; the last item can be a module or a package but can't be a
class or function or variable defined in the previous item.
## 6.4.1 Importing * From a Package
Now what happens when the user writes `from Sound.Effects import
*`? Ideally, one would hope that this somehow goes out to the
filesystem, finds which submodules are present in the package, and
imports them all. Unfortunately, this operation does not work very
well on Mac and Windows platforms, where the filesystem does not
always have accurate information about the case of a filename! On
these platforms, there is no guaranteed way to know whether a file
ECHO.PY should be imported as a module echo,
Echo or ECHO. (For example, Windows 95 has the
annoying practice of showing all file names with a capitalized first
letter.) The DOS 8+3 filename restriction adds another interesting
problem for long module names.
The only solution is for the package author to provide an explicit
index of the package. The import statement uses the following
convention: if a package's __init__.py code defines a list
named `__all__`, it is taken to be the list of module names that
should be imported when `from package import *` is
encountered. It is up to the package author to keep this list
up-to-date when a new version of the package is released. Package
authors may also decide not to support it, if they don't see a use for
importing * from their package. For example, the file
Sounds/Effects/__init__.py could contain the following code:
```text

__all__ = ["echo", "surround", "reverse"]
```
This would mean that `from Sound.Effects import *` would
import the three named submodules of the Sound package.
If `__all__` is not defined, the statement `from Sound.Effects
import *` does not import all submodules from the package
Sound.Effects into the current namespace; it only ensures that the
package Sound.Effects has been imported (possibly running its
initialization code, __init__.py) and then imports whatever names are
defined in the package. This includes any names defined (and
submodules explicitly loaded) by __init__.py. It also includes any
submodules of the package that were explicitly loaded by previous
import statements, e.g.
```text

import Sound.Effects.echo
import Sound.Effects.surround
from Sound.Effects import *
```
In this example, the echo and surround modules are imported in the
current namespace because they are defined in the
Sound.Effects package when the `from...import` statement
is executed. (This also works when `__all__` is defined.)
Note that in general the practicing of importing * from a module or
package is frowned upon, since it often causes poorly readable code.
However, it is okay to use it to save typing in interactive sessions,
and certain modules are designed to export only names that follow
certain patterns.
Remember, there is nothing wrong with using `from Package
import specific_submodule`! In fact, this is the
recommended notation unless the importing module needs to use
submodules with the same name from different packages.
## 6.4.2 Intra-package References
The submodules often need to refer to each other. For example, the
surround module might use the echo module. In fact, such references
are so common that the `import` statement first looks in the
containing package before looking in the standard module search path.
Thus, the surround module can simply use `import echo` or
`from echo import echofilter`. If the imported module is not
found in the current package (the package of which the current module
is a submodule), the `import` statement looks for a top-level module
with the given name.
When packages are structured into subpackages (as with the
Sound package in the example), there's no shortcut to refer
to submodules of sibling packages - the full name of the subpackage
must be used. For example, if the module
Sound.Filters.vocoder needs to use the echo module
in the Sound.Effects package, it can use `from
Sound.Effects import echo`.


7. Input and Output

node8.html | tut.html | node10.html | Python Tutorial | node2.html
---
- 7.1 Fancier Output Formatting (node9.html#SECTION009100000000000000000)
  7.2 Reading and Writing Files (node9.html#SECTION009200000000000000000)
  - 7.2.1 Methods of File Objects (node9.html#SECTION009210000000000000000)
  7.2.2 The pickle Module (node9.html#SECTION009220000000000000000)
---
# 7. Input and Output
There are several ways to present the output of a program; data can be
printed in a human-readable form, or written to a file for future use.
This chapter will discuss some of the possibilities.
# 7.1 Fancier Output Formatting
So far we've encountered two ways of writing values: expression
statements and the print statement. (A third way is using
the write() method of file objects; the standard output file
can be referenced as `sys.stdout`. See the Library Reference for
more information on this.)
Often you'll want more control over the formatting of your output than
simply printing space-separated values. There are two ways to format
your output; the first way is to do all the string handling yourself;
using string slicing and concatenation operations you can create any
lay-out you can imagine. The standard module
string contains some useful operations
for padding strings to a given column width; these will be discussed
shortly. The second way is to use the `%` operator with a
string as the left argument. The `%` operator interprets the
left argument as a C much like a sprintf()-style format
string to be applied to the right argument, and returns the string
resulting from this formatting operation.
One question remains, of course: how do you convert values to strings?
Luckily, Python has a way to convert any value to a string: pass it to
the repr() function, or just write the value between
reverse quotes (````). Some examples:
```text

>>> x = 10 * 3.14
>>> y = 200*200
>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
>>> print s
The value of x is 31.4, and y is 40000...
>>> # Reverse quotes work on other types besides numbers:
... p = [x, y]
>>> ps = repr(p)
>>> ps
'[31.4, 40000]'
>>> # Converting a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = `hello`
>>> print hellos
'hello, world\012'
>>> # The argument of reverse quotes may be a tuple:
... `x, y, ('spam', 'eggs')`
"(31.4, 40000, ('spam', 'eggs'))"
```
Here are two ways to write a table of squares and cubes:
```text

>>> import string
>>> for x in range(1, 11):
... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
... # Note trailing comma on previous line
... print string.rjust(`x*x*x`, 4)
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
>>> for x in range(1,11):
... print '%2d %3d %4d' % (x, x*x, x*x*x)
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
```
(Note that one space between each column was added by the way
print works: it always adds spaces between its arguments.)
This example demonstrates the function string.rjust(),
which right-justifies a string in a field of a given width by padding
it with spaces on the left. There are similar functions
string.ljust() and string.center(). These
functions do not write anything, they just return a new string. If
the input string is too long, they don't truncate it, but return it
unchanged; this will mess up your column lay-out but that's usually
better than the alternative, which would be lying about a value. (If
you really want truncation you can always add a slice operation, as in
"string.ljust(x, n)[0:n]".)
There is another function, string.zfill(), which pads a
numeric string on the left with zeros. It understands about plus and
minus signs:
```text

>>> import string
>>> string.zfill('12', 5)
'00012'
>>> string.zfill('-3.14', 7)
'-003.14'
>>> string.zfill('3.14159265359', 5)
'3.14159265359'
```
Using the `%` operator looks like this:
```text

>>> import math
>>> print 'The value of PI is approximately %5.3f.' % math.pi
The value of PI is approximately 3.142.
```
If there is more than one format in the string you pass a tuple as
right operand, e.g.
```text

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print '%-10s ==> %10d' % (name, phone)
...
Jack ==> 4098
Dcab ==> 7678
Sjoerd ==> 4127
```
Most formats work exactly as in C and require that you pass the proper
type; however, if you don't you get an exception, not a core dump.
The `%s` format is more relaxed: if the corresponding argument is
not a string object, it is converted to string using the
str() built-in function. Using `*` to pass the width
or precision in as a separate (integer) argument is supported. The
C formats `%n` and `%p` are not supported.
If you have a really long format string that you don't want to split
up, it would be nice if you could reference the variables to be
formatted by name instead of by position. This can be done by using
an extension of C formats using the form `%(name)format`, e.g.
```text

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
```
This is particularly useful in combination with the new built-in
vars() function, which returns a dictionary containing all
local variables.
# 7.2 Reading and Writing Files
open() returns a file
object, and is most commonly used with two arguments:
"open(filename, mode)".
```text

>>> f=open('/tmp/workfile', 'w')
>>> print f
<open file '/tmp/workfile', mode 'w' at 80a0960>
```
The first argument is a string containing the filename. The second
argument is another string containing a few characters describing the
way in which the file will be used. mode can be `'r'` when
the file will only be read, `'w'` for only writing (an existing
file with the same name will be erased), and `'a'` opens the file
for appending; any data written to the file is automatically added to
the end. `'r+'` opens the file for both reading and writing.
The mode argument is optional; `'r'` will be assumed if
it's omitted.
On Windows and the Macintosh, `'b'` appended to the
mode opens the file in binary mode, so there are also modes like
`'rb'`, `'wb'`, and `'r+b'`. Windows makes a
distinction between text and binary files; the end-of-line characters
in text files are automatically altered slightly when data is read or
written. This behind-the-scenes modification to file data is fine for
ASCII text files, but it'll corrupt binary data like that in JPEGs or
.EXE files. Be very careful to use binary mode when reading and
writing such files. (Note that the precise semantics of text mode on
the Macintosh depends on the underlying C library being used.)
## 7.2.1 Methods of File Objects
The rest of the examples in this section will assume that a file
object called `f` has already been created.
To read a file's contents, call `f.read( size )`, which reads
some quantity of data and returns it as a string. size is an
optional numeric argument. When size is omitted or negative,
the entire contents of the file will be read and returned; it's your
problem if the file is twice as large as your machine's memory.
Otherwise, at most size bytes are read and returned. If the end
of the file has been reached, `f.read()` will return an empty
string (`""`).
```text

>>> f.read()
'This is the entire file.\012'
>>> f.read()
''
```
`f.readline()` reads a single line from the file; a newline
character (`\n`) is left at the end of the string, and is only
omitted on the last line of the file if the file doesn't end in a
newline. This makes the return value unambiguous; if
`f.readline()` returns an empty string, the end of the file has
been reached, while a blank line is represented by `'\n'`, a
string containing only a single newline.
```text

>>> f.readline()
'This is the first line of the file.\012'
>>> f.readline()
'Second line of the file\012'
>>> f.readline()
''
```
`f.readlines()` returns a list containing all the lines of data
in the file. If given an optional parameter sizehint, it reads
that many bytes from the file and enough more to complete a line, and
returns the lines from that. This is often used to allow efficient
reading of a large file by lines, but without having to load the
entire file in memory. Only complete lines will be returned.
```text

>>> f.readlines()
['This is the first line of the file.\012', 'Second line of the file\012']
```
`f.write( string )` writes the contents of string to
the file, returning `None`.
```text

>>> f.write('This is a test\n')
```
`f.tell()` returns an integer giving the file object's current
position in the file, measured in bytes from the beginning of the
file. To change the file object's position, use
"f.seek(offset, from_what)". The position is
computed from adding offset to a reference point; the reference
point is selected by the from_what argument. A
from_what value of 0 measures from the beginning of the file, 1
uses the current file position, and 2 uses the end of the file as the
reference point. from_what can be omitted and defaults to 0,
using the beginning of the file as the reference point.
```text

>>> f=open('/tmp/workfile', 'r+')
>>> f.write('0123456789abcdef')
>>> f.seek(5) # Go to the 5th byte in the file
>>> f.read(1)
'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
>>> f.read(1)
'd'
```
When you're done with a file, call `f.close()` to close it and
free up any system resources taken up by the open file. After calling
`f.close()`, attempts to use the file object will automatically fail.
```text

>>> f.close()
>>> f.read()
Traceback (innermost last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
```
File objects have some additional methods, such as
isatty() and truncate() which are less frequently
used; consult the Library Reference for a complete guide to file
objects.
## 7.2.2 The pickle Module
Strings can easily be written to and read from a file. Numbers take a
bit more effort, since the read() method only returns
strings, which will have to be passed to a function like
string.atoi(), which takes a string like `'123'` and
returns its numeric value 123. However, when you want to save more
complex data types like lists, dictionaries, or class instances,
things get a lot more complicated.
Rather than have users be constantly writing and debugging code to
save complicated data types, Python provides a standard module called
pickle. This is an amazing module that can take almost
any Python object (even some forms of Python code!), and convert it to
a string representation; this process is called pickling.
Reconstructing the object from the string representation is called
unpickling. Between pickling and unpickling, the string
representing the object may have been stored in a file or data, or
sent over a network connection to some distant machine.
If you have an object `x`, and a file object `f` that's been
opened for writing, the simplest way to pickle the object takes only
one line of code:
```text

pickle.dump(x, f)
```
To unpickle the object again, if `f` is a file object which has
been opened for reading:
```text

x = pickle.load(f)
```
(There are other variants of this, used when pickling many objects or
when you don't want to write the pickled data to a file; consult the
complete documentation for pickle in the Library Reference.)
pickle is the standard way to make Python objects which can
be stored and reused by other programs or by a future invocation of
the same program; the technical term for this is a
persistent object. Because pickle is so widely used,
many authors who write Python extensions take care to ensure that new
data types such as matrices can be properly pickled and unpickled.


Python Tutorial

../index.html | node1.html | Python Tutorial | node2.html
---
# Python Tutorial
Guido van Rossum
Fred L. Drake, Jr., editor
BeOpen PythonLabs
E-mail: python-docs@python.org
October 16, 2000
Release 2.0