Archive:Think Python/Files: Difference between revisions
wikademia>Whiteknight m Think Python: Automatically uploading HTML source of this book from http://www.greenteapress.com/thinkpython/html/. Will convert to wikitext in a separate step |
wikademia>Wikademia m moved Think Python/Files to Archive:Think Python/Files |
||
| (2 intermediate revisions by 2 users not shown) | |||
| Line 1: | Line 1: | ||
{{Think Python/Page}} | |||
== Chapter 14  Files == | |||
=== 14.1  Persistence === | |||
Most of the programs we have seen so far are transient in the | |||
sense that they run for a short time and produce some output, | sense that they run for a short time and produce some output, | ||
but when they end, their data disappears. If you run the program | but when they end, their data disappears. If you run the program | ||
again, it starts with a clean slate. | again, it starts with a clean slate. | ||
Other programs are '''persistent''': they run for a long time | |||
(or all the time); they keep at least some of their data | (or all the time); they keep at least some of their data | ||
in permanent storage (a hard drive, for example); and | in permanent storage (a hard drive, for example); and | ||
if they shut down and restart, they pick up where they left off. | if they shut down and restart, they pick up where they left off. | ||
Examples of persistent programs are operating systems, which | |||
run pretty much whenever a computer is on, and web servers, | run pretty much whenever a computer is on, and web servers, | ||
which run all the time, waiting for requests to come in on | which run all the time, waiting for requests to come in on | ||
the network. | the network. | ||
One of the simplest ways for programs to maintain their data | |||
is by reading and writing text files. We have already seen | is by reading and writing text files. We have already seen | ||
programs that read text files; in this chapters we will see programs | programs that read text files; in this chapters we will see programs | ||
that write them. | that write them. | ||
An alternative is to store the state of the program in a database. | |||
In this chapter I will present a simple database and a module, | In this chapter I will present a simple database and a module, | ||
<TT>pickle</TT>, that makes it easy to store program data. | |||
=== 14.2  Reading and writing === | |||
A text file is a sequence of characters stored on a permanent | |||
medium like a hard drive, flash memory, or CD-ROM. We saw how | medium like a hard drive, flash memory, or CD-ROM. We saw how | ||
to open and read a file in Section  | to open and read a file in Section 9.1. | ||
To write a file, you have to open it with mode | |||
<CODE>'w'</CODE> as a second parameter: | |||
<PRE CLASS="verbatim">>>> fout = open('output.txt', 'w') | |||
>>> print fout | >>> print fout | ||
<open file 'output.txt', mode 'w' at 0xb7eb2410> | <open file 'output.txt', mode 'w' at 0xb7eb2410> | ||
</PRE> | |||
If the file already exists, opening it in write mode clears out | |||
the old data and starts fresh, so be careful! | the old data and starts fresh, so be careful! | ||
If the file doesn’t exist, a new one is created. | If the file doesn’t exist, a new one is created. | ||
The <TT>write</TT> method puts data into the file. | |||
<PRE CLASS="verbatim">>>> line1 = "This here's the wattle,\n" | |||
>>> fout.write(line1) | >>> fout.write(line1) | ||
</PRE> | |||
you call | Again, the file object keeps track of where it is, so if | ||
you call <TT>write</TT> again, it adds the new data to the end. | |||
<PRE CLASS="verbatim">>>> line2 = "the emblem of our land.\n" | |||
>>> fout.write(line2) | >>> fout.write(line2) | ||
</PRE> | |||
When you are done writing, you have to close the file. | |||
<PRE CLASS="verbatim">>>> fout.close() | |||
</PRE> | |||
=== 14.3  Format operator === | |||
The argument of <TT>write</TT> has to be a string, so if we want | |||
to put other values in a file, we have to convert them to | to put other values in a file, we have to convert them to | ||
strings. The easiest way to do that is with | strings. The easiest way to do that is with <TT>str</TT>: | ||
<PRE CLASS="verbatim">>>> x = 52 | |||
>>> f.write(str(x)) | >>> f.write(str(x)) | ||
</PRE> | |||
applied to integers, | An alternative is to use the '''format operator''', <TT>%</TT>. When | ||
when the first operand is a string, | applied to integers, <TT>%</TT> is the modulus operator. But | ||
when the first operand is a string, <TT>%</TT> is the format operator. | |||
The first operand is the '''format string''', and the second operand | |||
is a tuple of expressions. The result is a string that contains | is a tuple of expressions. The result is a string that contains | ||
the values of the expressions, formatted according to the format | the values of the expressions, formatted according to the format | ||
string. | string. | ||
As an example, the '''format sequence''' <CODE>'%d'</CODE> means that | |||
the first expression in the tuple should be formatted as an | the first expression in the tuple should be formatted as an | ||
integer ( | integer (<TT>d</TT> stands for “decimal”): | ||
<PRE CLASS="verbatim">>>> camels = 42 | |||
>>> '%d' % camels | >>> '%d' % camels | ||
'42' | '42' | ||
</PRE> | |||
with the integer value | The result is the string <CODE>'42'</CODE>, which is not to be confused | ||
so you can embed a value in a sentence: | with the integer value <TT>42</TT>. | ||
A format sequence can appear anywhere in the format string, | |||
so you can embed a value in a sentence: | |||
<PRE CLASS="verbatim">>>> camels = 42 | |||
>>> 'I have spotted %d camels.' % camels | >>> 'I have spotted %d camels.' % camels | ||
'I have spotted 42 camels.' | 'I have spotted 42 camels.' | ||
</PRE> | |||
as a floating-point number (don’t ask why), and | The format sequence <CODE>'%g'</CODE> formats the next element in the tuple | ||
the next item as a string: | as a floating-point number (don’t ask why), and <CODE>'%s'</CODE> formats | ||
the next item as a string: | |||
<PRE CLASS="verbatim">>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels') | |||
'In 3 years I have spotted 0.1 camels.' | 'In 3 years I have spotted 0.1 camels.' | ||
</PRE> | |||
The number of elements in the tuple has to match the number | |||
of format sequences in the string. Also, the types of the | of format sequences in the string. Also, the types of the | ||
elements have to match the format sequences: | elements have to match the format sequences: | ||
<PRE CLASS="verbatim">>>> '%d %d %d' % (1, 2) | |||
TypeError: not enough arguments for format string | TypeError: not enough arguments for format string | ||
>>> '%d' % 'dollars' | >>> '%d' % 'dollars' | ||
TypeError: illegal argument type for built-in operation | TypeError: illegal argument type for built-in operation | ||
</PRE> | |||
second, the element is the wrong type. | In the first example, there aren’t enough elements; in the | ||
read more about it at | second, the element is the wrong type. | ||
The format operator is powerful but difficult to use. You can | |||
read more about it at <TT>docs.python.org/lib/typesseq-strings.html</TT>. | |||
=== 14.4  Filenames and paths === | |||
Files are organized into '''directories''' (also called “folders”). | |||
Every running program has a “current directory,” which is the | Every running program has a “current directory,” which is the | ||
default directory for most operations. | default directory for most operations. | ||
For example, when you open a file for reading, Python looks for it in the | For example, when you open a file for reading, Python looks for it in the | ||
current directory. | current directory. | ||
directories (“os” stands for “operating system”). | |||
returns the name of the current directory: | |||
The <TT>os</TT> module provides functions for working with files and | |||
directories (“os” stands for “operating system”). <TT>os.getcwd</TT> | |||
returns the name of the current directory: | |||
<PRE CLASS="verbatim">>>> import os | |||
>>> cwd = os.getcwd() | >>> cwd = os.getcwd() | ||
>>> print cwd | >>> print cwd | ||
/home/dinsdale | /home/dinsdale | ||
</PRE> | |||
this example is | <TT>cwd</TT> stands for “current working directory.” The result in | ||
user named | this example is <TT>/home/dinsdale</TT>, which is the home directory of a | ||
user named <TT>dinsdale</TT>. | |||
A | |||
an | |||
file system. | |||
A string like <TT>cwd</TT> that identifies a file is called a '''path'''. | |||
A '''relative path''' starts from the current directory; | |||
an '''absolute path''' starts from the topmost directory in the | |||
file system. | |||
The paths we have seen so far are simple filenames, so they are | |||
relative to the current directory. To find the absolute path to | relative to the current directory. To find the absolute path to | ||
a file, you can use | a file, you can use <TT>os.path.abspath</TT>: | ||
<PRE CLASS="verbatim">>>> os.path.abspath('memo.txt') | |||
'/home/dinsdale/memo.txt' | '/home/dinsdale/memo.txt' | ||
</PRE> | |||
whether a file or directory exists: | <TT>os.path.exists</TT> checks | ||
whether a file or directory exists: | |||
<PRE CLASS="verbatim">>>> os.path.exists('memo.txt') | |||
True | True | ||
</PRE> | |||
If it exists, <TT>os.path.isdir</TT> checks whether it’s a directory: | |||
<PRE CLASS="verbatim">>>> os.path.isdir('memo.txt') | |||
False | False | ||
>>> os.path.isdir('music') | >>> os.path.isdir('music') | ||
True | True | ||
</PRE> | |||
in the given directory: | Similarly, <TT>os.path.isfile</TT> checks whether it’s a file. | ||
<TT>os.listdir</TT> returns a list of the files (and other directories) | |||
in the given directory: | |||
<PRE CLASS="verbatim">>>> os.listdir(cwd) | |||
['music', 'photos', 'memo.txt'] | ['music', 'photos', 'memo.txt'] | ||
</PRE> | |||
To demonstrate these functions, the following example | |||
“walks” through a directory, prints | “walks” through a directory, prints | ||
the names of all the files, and calls itself recursively on | the names of all the files, and calls itself recursively on | ||
all the directories. | all the directories. | ||
<PRE CLASS="verbatim">def walk(dir): | |||
for name in os.listdir(dir): | for name in os.listdir(dir): | ||
path = os.path.join(dir, name) | path = os.path.join(dir, name) | ||
| Line 131: | Line 213: | ||
else: | else: | ||
walk(path) | walk(path) | ||
</PRE> | |||
them into a complete path. | <TT>os.path.join</TT> takes a directory and a file name and joins | ||
Modify | them into a complete path. | ||
<DIV CLASS="theorem">'''Exercise 1'''  '' | |||
Modify ''''<TT>walk</TT>'''' so that instead of printing the names of | |||
the files, it returns a list of names. | the files, it returns a list of names. | ||
''</DIV><DIV CLASS="theorem">'''Exercise 2'''  '' | |||
The | The ''''<TT>os</TT>'''' module provides a function called ''''<TT>walk</TT>'''' | ||
that is similar to this one but more versatile. Read | that is similar to this one but more versatile. Read | ||
the documentation and use it to print the names of the | the documentation and use it to print the names of the | ||
files in a given directory and its subdirectories. | files in a given directory and its subdirectories. | ||
''</DIV>=== 14.5  Catching exceptions === | |||
A lot of things can go wrong when you try to read and write | |||
files. If you try to open a file that doesn’t exist, you get an | files. If you try to open a file that doesn’t exist, you get an | ||
<TT>IOError</TT>: | |||
<PRE CLASS="verbatim">>>> fin = open('bad_file') | |||
IOError: [Errno 2] No such file or directory: 'bad_file' | IOError: [Errno 2] No such file or directory: 'bad_file' | ||
</PRE> | |||
If you don’t have permission to access a file: | |||
<PRE CLASS="verbatim">>>> fout = open('/etc/passwd', 'w') | |||
IOError: [Errno 13] Permission denied: '/etc/passwd' | IOError: [Errno 13] Permission denied: '/etc/passwd' | ||
</PRE> | |||
And if you try to open a directory for reading, you get | |||
<PRE CLASS="verbatim">>>> fin = open('/home') | |||
IOError: [Errno 21] Is a directory | IOError: [Errno 21] Is a directory | ||
</PRE> | |||
and | To avoid these errors, you could use functions like <TT>os.path.exists</TT> | ||
to check all the possibilities (if “ | and <TT>os.path.isfile</TT>, but it would take a lot of time and code | ||
indication, there are at least 21 things that can go wrong). | to check all the possibilities (if “<TT>Errno 21</TT>” is any | ||
indication, there are at least 21 things that can go wrong). | |||
happen, which is exactly what the | |||
syntax is similar to an | |||
It is better to go ahead and try, and deal with problems if they | |||
happen, which is exactly what the <TT>try</TT> statement does. The | |||
syntax is similar to an <TT>if</TT> statement: | |||
<PRE CLASS="verbatim">try: | |||
fin = open('bad_file') | fin = open('bad_file') | ||
for line in fin: | for line in fin: | ||
| Line 167: | Line 270: | ||
except: | except: | ||
print 'Something went wrong.' | print 'Something went wrong.' | ||
</PRE> | |||
well, it skips the | Python starts by executing the <TT>try</TT> clause. If all goes | ||
exception occurs, it jumps out of the | well, it skips the <TT>except</TT> clause and proceeds. If an | ||
executes the | exception occurs, it jumps out of the <TT>try</TT> clause and | ||
executes the <TT>except</TT> clause. | |||
Handling an exception with a <TT>try</TT> statement is called '''catching''' an exception. In this example, the <TT>except</TT> clause | |||
prints an error message that is not very helpful. In general, | prints an error message that is not very helpful. In general, | ||
catching an exception gives you a chance to fix the problem, or try | catching an exception gives you a chance to fix the problem, or try | ||
again, or at least end the program gracefully. | again, or at least end the program gracefully. | ||
=== 14.6  Databases === | |||
A '''database''' is a file that is organized for storing data. | |||
Most databases are organized like a dictionary in the sense | Most databases are organized like a dictionary in the sense | ||
that they map from keys to values. The biggest difference | that they map from keys to values. The biggest difference | ||
is that the database is on disk (or other permanent storage), | is that the database is on disk (or other permanent storage), | ||
so it persists after the program ends. | so it persists after the program ends. | ||
The module <TT>anydbm</TT> provides an interface for creating | |||
and updating database files. As an example, I’ll create a database | and updating database files. As an example, I’ll create a database | ||
that contains captions for image files. | that contains captions for image files. | ||
to opening other files: | |||
Opening a database is similar | |||
to opening other files: | |||
<PRE CLASS="verbatim">>>> import anydbm | |||
>>> db = anydbm.open('captions.db', 'c') | >>> db = anydbm.open('captions.db', 'c') | ||
</PRE> | |||
The mode <CODE>'c'</CODE> means that the database should be created if | |||
it doesn’t already exist. The result is a database object | it doesn’t already exist. The result is a database object | ||
that can be used (for most operations) like a dictionary. | that can be used (for most operations) like a dictionary. | ||
If you create a new item, | If you create a new item, <TT>anydbm</TT> updates the database file. | ||
<PRE CLASS="verbatim">>>> db['cleese.png'] = 'Photo of John Cleese.' | |||
</PRE> | |||
When you access one of the items, <TT>anydbm</TT> reads the file: | |||
<PRE CLASS="verbatim">>>> print db['cleese.png'] | |||
Photo of John Cleese. | Photo of John Cleese. | ||
</PRE> | |||
the old value: | If you make another assignment to an existing key, <TT>anydbm</TT> replaces | ||
the old value: | |||
<PRE CLASS="verbatim">>>> db['cleese.png'] = 'Photo of John Cleese doing a silly walk.' | |||
>>> print db['cleese.png'] | >>> print db['cleese.png'] | ||
Photo of John Cleese doing a silly walk. | Photo of John Cleese doing a silly walk. | ||
</PRE> | |||
work with database objects. So does iteration with a | Many dictionary methods, like <TT>keys</TT> and <TT>items</TT>, also | ||
statement. | work with database objects. So does iteration with a <TT>for</TT> | ||
statement. | |||
<PRE CLASS="verbatim">for key in db: | |||
print key | print key | ||
</PRE> | |||
done: | As with other files, you should close the database when you are | ||
done: | |||
<PRE CLASS="verbatim">>>> db.close() | |||
</PRE> | |||
=== 14.7  Pickling === | |||
A limitation of <TT>anydbm</TT> is that the keys and values have | |||
to be strings. If you try to use any other type, you get an | to be strings. If you try to use any other type, you get an | ||
error. | error. | ||
The <TT>pickle</TT> module can help. It translates | |||
almost any type of object into a string suitable for storage in a | almost any type of object into a string suitable for storage in a | ||
database, and then translates strings back into objects. | database, and then translates strings back into objects. | ||
a string representation ( | |||
<TT>pickle.dumps</TT> takes an object as a parameter and returns | |||
a string representation (<TT>dumps</TT> is short for “dump string”): | |||
<PRE CLASS="verbatim">>>> import pickle | |||
>>> t = [1, 2, 3] | >>> t = [1, 2, 3] | ||
>>> pickle.dumps(t) | >>> pickle.dumps(t) | ||
'(lp0\nI1\naI2\naI3\na.' | '(lp0\nI1\naI2\naI3\na.' | ||
</PRE> | |||
easy for | The format isn’t obvious to human readers; it is meant to be | ||
(“load string”) reconstitutes the object: | easy for <TT>pickle</TT> to interpret. <TT>pickle.loads</TT> | ||
(“load string”) reconstitutes the object: | |||
<PRE CLASS="verbatim">>>> t1 = [1, 2, 3] | |||
>>> s = pickle.dumps(t1) | >>> s = pickle.dumps(t1) | ||
>>> t2 = pickle.loads(s) | >>> t2 = pickle.loads(s) | ||
>>> print t2 | >>> print t2 | ||
[1, 2, 3] | [1, 2, 3] | ||
</PRE> | |||
not (in general) the same object: | Although the new object has the same value as the old, it is | ||
not (in general) the same object: | |||
<PRE CLASS="verbatim">>>> t == t2 | |||
True | True | ||
>>> t is t2 | >>> t is t2 | ||
False | False | ||
</PRE> | |||
as copying the object. | In other words, pickling and then unpickling has the same effect | ||
as copying the object. | |||
You can use <TT>pickle</TT> to store non-strings in a database. | |||
In fact, this combination is so common that it has been | In fact, this combination is so common that it has been | ||
encapsulated in a module called | encapsulated in a module called <TT>shelve</TT>. | ||
<DIV CLASS="theorem">'''Exercise 3'''   | |||
'' | |||
'' | |||
''If you did Exercise ''''12.4'''', modify your solution so that | |||
it creates a database that maps from each word in the list to | it creates a database that maps from each word in the list to | ||
a list of words that use the same set of letters. | a list of words that use the same set of letters.'' | ||
''Write a different program that opens the database and prints | |||
the contents in a human-readable format. | the contents in a human-readable format. | ||
'' | |||
</DIV>=== 14.8  Pipes === | |||
also known as a | |||
Most operating systems provide a command-line interface, | |||
also known as a '''shell'''. Shells usually provide commands | |||
to navigate the file system and launch applications. For | to navigate the file system and launch applications. For | ||
example, in Unix, you can change directories with | example, in Unix, you can change directories with <TT>cd</TT>, | ||
display the contents of a directory with | display the contents of a directory with <TT>ls</TT>, and launch | ||
a web browser by typing (for example) | a web browser by typing (for example) <TT>firefox</TT>. | ||
launched from Python using a | |||
that represents a running process. | |||
Any program that you can launch from the shell can also be | |||
launched from Python using a '''pipe'''. A pipe is an object | |||
that represents a running process. | |||
For example, the Unix command <TT>ls -l</TT> normally displays the | |||
contents of the current directory (in long format). You can | contents of the current directory (in long format). You can | ||
launch | launch <TT>ls</TT> with <TT>os.popen</TT>: | ||
<PRE CLASS="verbatim">>>> cmd = 'ls -l' | |||
>>> fp = os.popen(cmd) | >>> fp = os.popen(cmd) | ||
</PRE> | |||
The argument is a string that contains a shell command. The | |||
return value is a file pointer that behaves just like an open | return value is a file pointer that behaves just like an open | ||
file. You can read the output from the | file. You can read the output from the <TT>ls</TT> process one | ||
line at a time with | line at a time with <TT>readline</TT> or get the whole thing at | ||
once with | once with <TT>read</TT>: | ||
<PRE CLASS="verbatim">>>> res = fp.read() | |||
</PRE> | |||
When you are done, you close the pipe like a file: | |||
<PRE CLASS="verbatim">>>> stat = fp.close() | |||
>>> print stat | >>> print stat | ||
None | None | ||
</PRE> | |||
The return value is the final status of the <TT>ls</TT> process; | |||
<TT>None</TT> means that it ended normally (with no errors). | |||
A common use of pipes is to read a compressed file incrementally; | |||
that is, without uncompressing the whole thing at once. The | that is, without uncompressing the whole thing at once. The | ||
following function takes the name of a compressed file as a | following function takes the name of a compressed file as a | ||
parameter and returns a pipe that uses | parameter and returns a pipe that uses <TT>gzip</TT> to decompress | ||
the contents: | the contents: | ||
<PRE CLASS="verbatim">def open_gzip(filename): | |||
cmd = 'gunzip -c ' + filename | cmd = 'gunzip -c ' + filename | ||
fp = os.popen(cmd) | fp = os.popen(cmd) | ||
return fp | return fp | ||
</PRE> | |||
to store the uncompressed file in memory or on disk. | If you read lines from <TT>fp</TT> one at a time, you never have | ||
to store the uncompressed file in memory or on disk. | |||
=== 14.9  Writing modules === | |||
For example, suppose you have a file named | |||
code: | |||
Any file that contains Python code can be imported as a module. | |||
For example, suppose you have a file named <TT>wc.py</TT> with the following | |||
code: | |||
<PRE CLASS="verbatim">def linecount(filename): | |||
count = 0 | count = 0 | ||
for line in open(filename): | for line in open(filename): | ||
| Line 282: | Line 475: | ||
print linecount('wc.py') | print linecount('wc.py') | ||
</PRE> | |||
If you run this program, it reads itself and prints the number | |||
of lines in the file, which is 7. | of lines in the file, which is 7. | ||
You can also import it like this: | You can also import it like this: | ||
<PRE CLASS="verbatim">>>> import wc | |||
7 | 7 | ||
</PRE> | |||
Now you have a module object <TT>wc</TT>: | |||
<PRE CLASS="verbatim">>>> print wc | |||
<module 'wc' from 'wc.py'> | <module 'wc' from 'wc.py'> | ||
</PRE> | |||
That provides a function called <CODE>linecount</CODE>: | |||
<PRE CLASS="verbatim">>>> wc.linecount('wc.py') | |||
7 | 7 | ||
</PRE> | |||
So that’s how you write modules in Python. | |||
The only problem with this example is that when you import | |||
the module it executes the test code at the bottom. Normally | the module it executes the test code at the bottom. Normally | ||
when you import a module, it defines new functions but it | when you import a module, it defines new functions but it | ||
doesn’t execute them. | doesn’t execute them. | ||
use the following idiom: | |||
Programs that will be imported as modules often | |||
use the following idiom: | |||
<PRE CLASS="verbatim">if __name__ == '__main__': | |||
print linecount('wc.py') | print linecount('wc.py') | ||
</PRE> | |||
<CODE>__name__</CODE> is a built-in variable that is set when the | |||
program starts. If the program is running as a script, | program starts. If the program is running as a script, | ||
<CODE>__name__</CODE> has the value <CODE>__main__</CODE>; in that | |||
case, the test code is executed. Otherwise, | case, the test code is executed. Otherwise, | ||
if the module is being imported, the test code is skipped. | if the module is being imported, the test code is skipped. | ||
Type this example into a file named | <DIV CLASS="theorem">'''Exercise 4'''  '' | ||
Type this example into a file named ''''<TT>wc.py</TT>'''' and run | |||
it as a script. Then run the Python interpreter and | it as a script. Then run the Python interpreter and | ||
''''<TT>import wc</TT>''''. What is the value of ''<CODE>''__name__''</CODE>'' | |||
when the module is being imported? | when the module is being imported?'' | ||
''Warning: If you import a module that has already been imported, | |||
Python does nothing. It does not re-read the file, even if it has | Python does nothing. It does not re-read the file, even if it has | ||
changed. | changed.'' | ||
'' | |||
'''' | |||
'' | |||
''If you want to reload a module, you can use the built-in function | |||
''''<TT>reload</TT>'''', but it can be tricky, so the safest thing to do is | |||
restart the interpreter and then import the module again. | restart the interpreter and then import the module again. | ||
'' | |||
</DIV>=== 14.10  Debugging === | |||
When you are reading and writing files, you might run into problems | |||
with whitespace. These errors can be hard to debug because spaces, | with whitespace. These errors can be hard to debug because spaces, | ||
tabs and newlines are normally invisible: | tabs and newlines are normally invisible: | ||
<PRE CLASS="verbatim">>>> s = '1 2\t 3\n 4' | |||
>>> print s | >>> print s | ||
1 2 3 | 1 2 3 | ||
4 | 4 | ||
</PRE> | |||
The built-in function <TT>repr</TT> can help. It takes any object as an | |||
argument and returns a string representation of the object. For | argument and returns a string representation of the object. For | ||
strings, it represents whitespace | strings, it represents whitespace | ||
characters with backslash sequences: | characters with backslash sequences: | ||
<PRE CLASS="verbatim">>>> print repr(s) | |||
'1 2\t 3\n 4' | '1 2\t 3\n 4' | ||
</PRE> | |||
This can be helpful for debugging. | |||
One other problem you might run into is that different systems | |||
use different characters to indicate the end of a line. Some | use different characters to indicate the end of a line. Some | ||
systems use a newline, represented | systems use a newline, represented <CODE>\n</CODE>. Others use | ||
a return character, represented | a return character, represented <CODE>\r</CODE>. Some use both. | ||
If you move files between different systems, these inconsistencies | If you move files between different systems, these inconsistencies | ||
might cause problems. | might cause problems. | ||
For most systems, there are applications to convert from one | |||
format to another. You can find them (and read more about this | format to another. You can find them (and read more about this | ||
issue) at | issue) at <TT>wikipedia.org/wiki/Newline</TT>. Or, of course, you | ||
could write one yourself. | could write one yourself. | ||
=== 14.11  Glossary === | |||
<DL CLASS="description"><DT CLASS="dt-description">'''persistent:'''</DT><DD CLASS="dd-description"> Pertaining to a program that runs indefinitely | |||
and keeps at least some of its data in permanent storage. | and keeps at least some of its data in permanent storage. | ||
</DD><DT CLASS="dt-description">'''format operator:'''</DT><DD CLASS="dd-description"> An operator, <TT>%</TT>, that takes a format | |||
string and a tuple and generates a string that includes | string and a tuple and generates a string that includes | ||
the elements of the tuple formatted as specified by the format string. | the elements of the tuple formatted as specified by the format string. | ||
</DD><DT CLASS="dt-description">'''format string:'''</DT><DD CLASS="dd-description"> A string, used with the format operator, that | |||
contains format sequences. | contains format sequences. | ||
</DD><DT CLASS="dt-description">'''format sequence:'''</DT><DD CLASS="dd-description"> A sequence of characters in a format string, | |||
like | like <TT>%d</TT>, that specifies how a value should be formatted. | ||
</DD><DT CLASS="dt-description">'''text file:'''</DT><DD CLASS="dd-description"> A sequence of characters stored in permanent | |||
storage like a hard drive. | storage like a hard drive. | ||
</DD><DT CLASS="dt-description">'''directory:'''</DT><DD CLASS="dd-description"> A named collection of files, also called a folder. | |||
</DD><DT CLASS="dt-description">'''path:'''</DT><DD CLASS="dd-description"> A string that identifies a file. | |||
</DD><DT CLASS="dt-description">'''relative path:'''</DT><DD CLASS="dd-description"> A path that starts from the current directory. | |||
</DD><DT CLASS="dt-description">'''absolute path:'''</DT><DD CLASS="dd-description"> A path that starts from the topmost directory | |||
in the file system. | in the file system. | ||
</DD><DT CLASS="dt-description">'''catch:'''</DT><DD CLASS="dd-description"> To prevent an exception from terminating | |||
a program using the | a program using the <TT>try</TT> | ||
and | and <TT>except</TT> statements. | ||
</DD><DT CLASS="dt-description">'''database:'''</DT><DD CLASS="dd-description"> A file whose contents are organized like a dictionary | |||
with keys that correspond to values. | with keys that correspond to values. | ||
</DD></DL>=== 14.12  Exercises === | |||
<DIV CLASS="theorem">'''Exercise 5'''  '' | |||
'' | |||
'' | |||
'''' | |||
'' | |||
''The ''''<TT>urllib</TT>'''' module provides methods for manipulating URLs | |||
and downloading information from the web. The following example | and downloading information from the web. The following example | ||
downloads and prints a secret message from | downloads and prints a secret message from ''''<TT>thinkpython.com</TT>'''':'' | ||
<PRE CLASS="verbatim">''import urllib | |||
conn = urllib.urlopen('http://thinkpython.com/secret.html') | conn = urllib.urlopen('http://thinkpython.com/secret.html') | ||
for line in conn.fp: | for line in conn.fp: | ||
print line.strip() | print line.strip() | ||
''</PRE> | |||
''Run this code and follow the instructions you see there.'' | |||
'' | |||
'' | |||
</DIV><DIV CLASS="theorem">'''Exercise 6'''  '' | |||
'' | |||
''In a large collection of MP3 files, there may be more than one | |||
copy of the same song, stored in different directories or with | copy of the same song, stored in different directories or with | ||
different file names. The goal of this exercise is to search for | different file names. The goal of this exercise is to search for | ||
these duplicates. | these duplicates.'' | ||
*''Write a program that searches a directory and all of its | |||
subdirectories, recursively, and returns a list of complete paths | subdirectories, recursively, and returns a list of complete paths | ||
for all files with a given suffix (like | for all files with a given suffix (like ''''<TT>.mp3</TT>''''). | ||
Hint: | Hint: ''''<TT>os.path</TT>'''' provides several useful functions for | ||
manipulating file and path names. | manipulating file and path names.'' | ||
'' | |||
'''' | |||
'''' | |||
'' | |||
*''To recognize duplicates, you can use a hash function that | |||
reads the file and generates a short summary | reads the file and generates a short summary | ||
of the contents. For example, | of the contents. For example, | ||
| Line 385: | Line 636: | ||
“message” and returns a 128-bit “checksum.” The probability | “message” and returns a 128-bit “checksum.” The probability | ||
is very small that two files with different contents will | is very small that two files with different contents will | ||
return the same checksum. | return the same checksum.'' | ||
a Unix system you can use the program | ''You can read about MD5 at ''''<TT>wikipedia.org/wiki/Md5</TT>''''. On | ||
compute checksums from Python. | a Unix system you can use the program ''''<TT>md5sum</TT>'''' and a pipe to | ||
compute checksums from Python.'' | |||
</DIV><DIV CLASS="theorem">'''Exercise 7'''   | |||
'' | |||
'''' | |||
'' | |||
''The Internet Movie Database (IMDb) is an online collection of | |||
information about movies. Their database is available | information about movies. Their database is available | ||
in plain text format, so it is reasonably easy to read from | in plain text format, so it is reasonably easy to read from | ||
Python. For this exercise, the files you need | Python. For this exercise, the files you need | ||
are | are ''''<TT>actors.list.gz</TT>'''' and ''''<TT>actresses.list.gz</TT>''''; you | ||
can download them from | can download them from ''''<TT>www.imdb.com/interfaces#plain</TT>''''.'' | ||
'' | |||
'''' | |||
'' | |||
''I have written a program that parses these files and | |||
splits them into actor names, movie titles, etc. You can | splits them into actor names, movie titles, etc. You can | ||
download it from | download it from ''''<TT>thinkpython.com/code/imdb.py</TT>''''.'' | ||
and prints one actor-movie pair per line. Or, if you | |||
imdb</TT> | ''If you run ''''<TT>imdb.py</TT>'''' as a script, it reads ''''<TT>actors.list.gz</TT>'''' | ||
and prints one actor-movie pair per line. Or, if you ''''<TT>import | |||
imdb</TT>'''' you can use the function ''<CODE>''process_file''</CODE>'' to, well, | |||
process the file. The arguments are a filename, a function | process the file. The arguments are a filename, a function | ||
object and an optional number of lines to process. Here is | object and an optional number of lines to process. Here is | ||
an example: | an example:'' | ||
<PRE CLASS="verbatim">''import imdb | |||
def print_info(actor, date, title, role): | def print_info(actor, date, title, role): | ||
| Line 409: | Line 673: | ||
imdb.process_file('actors.list.gz', print_info) | imdb.process_file('actors.list.gz', print_info) | ||
''</PRE> | |||
contents, and calls | ''When you call ''<CODE>''process_file''</CODE>'', it opens ''''<TT>filename</TT>'''', reads the | ||
contents, and calls ''<CODE>''print_info''</CODE>'' once for each line in the file. | |||
arguments and prints them. | ''<CODE>''print_info''</CODE>'' takes an actor, date, movie title and role as | ||
that maps from each actor to a list of his or her films. | arguments and prints them.'' | ||
*''Write a program that reads ''''<TT>actors.list.gz</TT>'''' and ''''<TT>actresses.list.gz</TT>'''' and uses ''''<TT>shelve</TT>'''' to build a database | |||
that maps from each actor to a list of his or her films.'' | |||
'' | |||
'' | |||
*''Two actors are “costars” if they have been in at least one | |||
movie together. Process the database you built in the previous step | movie together. Process the database you built in the previous step | ||
and build a second database that maps from each actor to a list of | and build a second database that maps from each actor to a list of | ||
his or her costars. | his or her costars.'' | ||
'' | |||
'' | |||
*''Write a program that can play the “Six Degrees of Kevin | |||
Bacon,” which you can read about at | Bacon,” which you can read about at | ||
''''<TT>wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon</TT>''''. This | |||
problem is challenging because it requires you to find the shortest | problem is challenging because it requires you to find the shortest | ||
path in a graph. You can read about shortest path algorithms | path in a graph. You can read about shortest path algorithms | ||
at | at ''''<TT>wikipedia.org/wiki/Shortest_path_problem</TT>''''.'' | ||
</DIV><HR> | |||
<IMG SRC="previous_motif.gif" ALT="Previous"> | |||
<IMG SRC="contents_motif.gif" ALT="Up"> | |||
<IMG SRC="next_motif.gif" ALT="Next"> | |||
Latest revision as of 20:09, 18 May 2009
Chapter 14 Files
14.1 Persistence
Most of the programs we have seen so far are transient in the sense that they run for a short time and produce some output, but when they end, their data disappears. If you run the program again, it starts with a clean slate.
Other programs are persistent: they run for a long time (or all the time); they keep at least some of their data in permanent storage (a hard drive, for example); and if they shut down and restart, they pick up where they left off.
Examples of persistent programs are operating systems, which run pretty much whenever a computer is on, and web servers, which run all the time, waiting for requests to come in on the network.
One of the simplest ways for programs to maintain their data is by reading and writing text files. We have already seen programs that read text files; in this chapters we will see programs that write them.
An alternative is to store the state of the program in a database. In this chapter I will present a simple database and a module, pickle, that makes it easy to store program data.
14.2 Reading and writing
A text file is a sequence of characters stored on a permanent medium like a hard drive, flash memory, or CD-ROM. We saw how to open and read a file in Section 9.1.
To write a file, you have to open it with mode
'w' as a second parameter:
>>> fout = open('output.txt', 'w')
>>> print fout
<open file 'output.txt', mode 'w' at 0xb7eb2410>
If the file already exists, opening it in write mode clears out the old data and starts fresh, so be careful! If the file doesn’t exist, a new one is created.
The write method puts data into the file.
>>> line1 = "This here's the wattle,\n" >>> fout.write(line1)
Again, the file object keeps track of where it is, so if you call write again, it adds the new data to the end.
>>> line2 = "the emblem of our land.\n" >>> fout.write(line2)
When you are done writing, you have to close the file.
>>> fout.close()
14.3 Format operator
The argument of write has to be a string, so if we want to put other values in a file, we have to convert them to strings. The easiest way to do that is with str:
>>> x = 52 >>> f.write(str(x))
An alternative is to use the format operator, %. When applied to integers, % is the modulus operator. But when the first operand is a string, % is the format operator.
The first operand is the format string, and the second operand is a tuple of expressions. The result is a string that contains the values of the expressions, formatted according to the format string.
As an example, the format sequence '%d' means that
the first expression in the tuple should be formatted as an
integer (d stands for “decimal”):
>>> camels = 42 >>> '%d' % camels '42'
The result is the string '42', which is not to be confused
with the integer value 42.
A format sequence can appear anywhere in the format string, so you can embed a value in a sentence:
>>> camels = 42 >>> 'I have spotted %d camels.' % camels 'I have spotted 42 camels.'
The format sequence '%g' formats the next element in the tuple
as a floating-point number (don’t ask why), and '%s' formats
the next item as a string:
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels') 'In 3 years I have spotted 0.1 camels.'
The number of elements in the tuple has to match the number of format sequences in the string. Also, the types of the elements have to match the format sequences:
>>> '%d %d %d' % (1, 2) TypeError: not enough arguments for format string >>> '%d' % 'dollars' TypeError: illegal argument type for built-in operation
In the first example, there aren’t enough elements; in the second, the element is the wrong type.
The format operator is powerful but difficult to use. You can read more about it at docs.python.org/lib/typesseq-strings.html.
14.4 Filenames and paths
Files are organized into directories (also called “folders”). Every running program has a “current directory,” which is the default directory for most operations. For example, when you open a file for reading, Python looks for it in the current directory.
The os module provides functions for working with files and
directories (“os” stands for “operating system”). os.getcwd
returns the name of the current directory:
>>> import os >>> cwd = os.getcwd() >>> print cwd /home/dinsdale
cwd stands for “current working directory.” The result in this example is /home/dinsdale, which is the home directory of a user named dinsdale.
A string like cwd that identifies a file is called a path.
A relative path starts from the current directory;
an absolute path starts from the topmost directory in the
file system.
The paths we have seen so far are simple filenames, so they are
relative to the current directory. To find the absolute path to
a file, you can use os.path.abspath:
>>> os.path.abspath('memo.txt')
'/home/dinsdale/memo.txt'
os.path.exists checks whether a file or directory exists:
>>> os.path.exists('memo.txt')
True
If it exists, os.path.isdir checks whether it’s a directory:
>>> os.path.isdir('memo.txt')
False
>>> os.path.isdir('music')
True
Similarly, os.path.isfile checks whether it’s a file.
os.listdir returns a list of the files (and other directories) in the given directory:
>>> os.listdir(cwd) ['music', 'photos', 'memo.txt']
To demonstrate these functions, the following example “walks” through a directory, prints the names of all the files, and calls itself recursively on all the directories.
def walk(dir):
for name in os.listdir(dir):
path = os.path.join(dir, name)
if os.path.isfile(path):
print path
else:
walk(path)
os.path.join takes a directory and a file name and joins them into a complete path.
Modify 'walk' so that instead of printing the names of the files, it returns a list of names.
The 'os' module provides a function called 'walk' that is similar to this one but more versatile. Read the documentation and use it to print the names of the files in a given directory and its subdirectories.
=== 14.5 Catching exceptions ===
A lot of things can go wrong when you try to read and write
files. If you try to open a file that doesn’t exist, you get an
IOError:
>>> fin = open('bad_file')
IOError: [Errno 2] No such file or directory: 'bad_file'
If you don’t have permission to access a file:
>>> fout = open('/etc/passwd', 'w')
IOError: [Errno 13] Permission denied: '/etc/passwd'
And if you try to open a directory for reading, you get
>>> fin = open('/home')
IOError: [Errno 21] Is a directory
To avoid these errors, you could use functions like os.path.exists and os.path.isfile, but it would take a lot of time and code to check all the possibilities (if “Errno 21” is any indication, there are at least 21 things that can go wrong).
It is better to go ahead and try, and deal with problems if they happen, which is exactly what the try statement does. The syntax is similar to an if statement:
try:
fin = open('bad_file')
for line in fin:
print line
fin.close()
except:
print 'Something went wrong.'
Python starts by executing the try clause. If all goes well, it skips the except clause and proceeds. If an exception occurs, it jumps out of the try clause and executes the except clause.
Handling an exception with a try statement is called catching an exception. In this example, the except clause prints an error message that is not very helpful. In general, catching an exception gives you a chance to fix the problem, or try again, or at least end the program gracefully.
14.6 Databases
A database is a file that is organized for storing data. Most databases are organized like a dictionary in the sense that they map from keys to values. The biggest difference is that the database is on disk (or other permanent storage), so it persists after the program ends.
The module anydbm provides an interface for creating
and updating database files. As an example, I’ll create a database
that contains captions for image files.
Opening a database is similar
to opening other files:
>>> import anydbm
>>> db = anydbm.open('captions.db', 'c')
The mode 'c' means that the database should be created if
it doesn’t already exist. The result is a database object
that can be used (for most operations) like a dictionary.
If you create a new item, anydbm updates the database file.
>>> db['cleese.png'] = 'Photo of John Cleese.'
When you access one of the items, anydbm reads the file:
>>> print db['cleese.png'] Photo of John Cleese.
If you make another assignment to an existing key, anydbm replaces the old value:
>>> db['cleese.png'] = 'Photo of John Cleese doing a silly walk.' >>> print db['cleese.png'] Photo of John Cleese doing a silly walk.
Many dictionary methods, like keys and items, also work with database objects. So does iteration with a for statement.
for key in db:
print key
As with other files, you should close the database when you are done:
>>> db.close()
14.7 Pickling
A limitation of anydbm is that the keys and values have to be strings. If you try to use any other type, you get an error.
The pickle module can help. It translates
almost any type of object into a string suitable for storage in a
database, and then translates strings back into objects.
pickle.dumps takes an object as a parameter and returns a string representation (dumps is short for “dump string”):
>>> import pickle >>> t = [1, 2, 3] >>> pickle.dumps(t) '(lp0\nI1\naI2\naI3\na.'
The format isn’t obvious to human readers; it is meant to be easy for pickle to interpret. pickle.loads (“load string”) reconstitutes the object:
>>> t1 = [1, 2, 3] >>> s = pickle.dumps(t1) >>> t2 = pickle.loads(s) >>> print t2 [1, 2, 3]
Although the new object has the same value as the old, it is not (in general) the same object:
>>> t == t2 True >>> t is t2 False
In other words, pickling and then unpickling has the same effect as copying the object.
You can use pickle to store non-strings in a database. In fact, this combination is so common that it has been encapsulated in a module called shelve.
If you did Exercise '12.4', modify your solution so that it creates a database that maps from each word in the list to a list of words that use the same set of letters.
Write a different program that opens the database and prints the contents in a human-readable format.
=== 14.8 Pipes ===
Most operating systems provide a command-line interface,
also known as a shell. Shells usually provide commands
to navigate the file system and launch applications. For
example, in Unix, you can change directories with cd,
display the contents of a directory with ls, and launch
a web browser by typing (for example) firefox.
Any program that you can launch from the shell can also be
launched from Python using a pipe. A pipe is an object
that represents a running process.
For example, the Unix command ls -l normally displays the contents of the current directory (in long format). You can launch ls with os.popen:
>>> cmd = 'ls -l' >>> fp = os.popen(cmd)
The argument is a string that contains a shell command. The return value is a file pointer that behaves just like an open file. You can read the output from the ls process one line at a time with readline or get the whole thing at once with read:
>>> res = fp.read()
When you are done, you close the pipe like a file:
>>> stat = fp.close() >>> print stat None
The return value is the final status of the ls process; None means that it ended normally (with no errors).
A common use of pipes is to read a compressed file incrementally;
that is, without uncompressing the whole thing at once. The
following function takes the name of a compressed file as a
parameter and returns a pipe that uses gzip to decompress
the contents:
def open_gzip(filename):
cmd = 'gunzip -c ' + filename
fp = os.popen(cmd)
return fp
If you read lines from fp one at a time, you never have to store the uncompressed file in memory or on disk.
14.9 Writing modules
Any file that contains Python code can be imported as a module. For example, suppose you have a file named wc.py with the following code:
def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
print linecount('wc.py')
If you run this program, it reads itself and prints the number of lines in the file, which is 7. You can also import it like this:
>>> import wc 7
Now you have a module object wc:
>>> print wc <module 'wc' from 'wc.py'>
That provides a function called linecount:
>>> wc.linecount('wc.py')
7
So that’s how you write modules in Python.
The only problem with this example is that when you import the module it executes the test code at the bottom. Normally when you import a module, it defines new functions but it doesn’t execute them.
Programs that will be imported as modules often
use the following idiom:
if __name__ == '__main__':
print linecount('wc.py')
__name__ is a built-in variable that is set when the
program starts. If the program is running as a script,
__name__ has the value __main__; in that
case, the test code is executed. Otherwise,
if the module is being imported, the test code is skipped.
Type this example into a file named 'wc.py' and run
it as a script. Then run the Python interpreter and
'import wc'. What is the value of __name__
when the module is being imported?
Warning: If you import a module that has already been imported,
Python does nothing. It does not re-read the file, even if it has
changed.
'
If you want to reload a module, you can use the built-in function 'reload', but it can be tricky, so the safest thing to do is restart the interpreter and then import the module again.
=== 14.10 Debugging ===
When you are reading and writing files, you might run into problems
with whitespace. These errors can be hard to debug because spaces,
tabs and newlines are normally invisible:
>>> s = '1 2\t 3\n 4' >>> print s 1 2 3 4
The built-in function repr can help. It takes any object as an
argument and returns a string representation of the object. For
strings, it represents whitespace
characters with backslash sequences:
>>> print repr(s) '1 2\t 3\n 4'
This can be helpful for debugging.
One other problem you might run into is that different systems
use different characters to indicate the end of a line. Some
systems use a newline, represented \n. Others use
a return character, represented \r. Some use both.
If you move files between different systems, these inconsistencies
might cause problems.
For most systems, there are applications to convert from one format to another. You can find them (and read more about this issue) at wikipedia.org/wiki/Newline. Or, of course, you could write one yourself.
14.11 Glossary
- persistent:
- Pertaining to a program that runs indefinitely and keeps at least some of its data in permanent storage.
- format operator:
- An operator, %, that takes a format string and a tuple and generates a string that includes the elements of the tuple formatted as specified by the format string.
- format string:
- A string, used with the format operator, that contains format sequences.
- format sequence:
- A sequence of characters in a format string, like %d, that specifies how a value should be formatted.
- text file:
- A sequence of characters stored in permanent storage like a hard drive.
- directory:
- A named collection of files, also called a folder.
- path:
- A string that identifies a file.
- relative path:
- A path that starts from the current directory.
- absolute path:
- A path that starts from the topmost directory in the file system.
- catch:
- To prevent an exception from terminating a program using the try and except statements.
- database:
- A file whose contents are organized like a dictionary with keys that correspond to values.
=== 14.12 Exercises ===
'
The 'urllib' module provides methods for manipulating URLs and downloading information from the web. The following example downloads and prints a secret message from 'thinkpython.com':
''import urllib
conn = urllib.urlopen('http://thinkpython.com/secret.html')
for line in conn.fp:
print line.strip()
''
Run this code and follow the instructions you see there.
In a large collection of MP3 files, there may be more than one copy of the same song, stored in different directories or with different file names. The goal of this exercise is to search for these duplicates.
- Write a program that searches a directory and all of its
subdirectories, recursively, and returns a list of complete paths for all files with a given suffix (like '.mp3'). Hint: 'os.path' provides several useful functions for manipulating file and path names. ' '
- To recognize duplicates, you can use a hash function that
reads the file and generates a short summary of the contents. For example, MD5 (Message-Digest algorithm 5) takes an arbitrarily-long “message” and returns a 128-bit “checksum.” The probability is very small that two files with different contents will return the same checksum. You can read about MD5 at 'wikipedia.org/wiki/Md5'. On a Unix system you can use the program 'md5sum' and a pipe to compute checksums from Python.
'
The Internet Movie Database (IMDb) is an online collection of information about movies. Their database is available in plain text format, so it is reasonably easy to read from Python. For this exercise, the files you need are 'actors.list.gz' and 'actresses.list.gz'; you can download them from 'www.imdb.com/interfaces#plain'.
'
I have written a program that parses these files and splits them into actor names, movie titles, etc. You can download it from 'thinkpython.com/code/imdb.py'.
If you run 'imdb.py' as a script, it reads 'actors.list.gz'
and prints one actor-movie pair per line. Or, if you 'import
imdb' you can use the function process_file to, well,
process the file. The arguments are a filename, a function
object and an optional number of lines to process. Here is
an example:
''import imdb
def print_info(actor, date, title, role):
print actor, date, title, role
imdb.process_file('actors.list.gz', print_info)
''
When you call process_file, it opens 'filename', reads the
contents, and calls print_info once for each line in the file.
print_info takes an actor, date, movie title and role as
arguments and prints them.
- Write a program that reads 'actors.list.gz' and 'actresses.list.gz' and uses 'shelve' to build a database
that maps from each actor to a list of his or her films.
- Two actors are “costars” if they have been in at least one
movie together. Process the database you built in the previous step and build a second database that maps from each actor to a list of his or her costars.
- Write a program that can play the “Six Degrees of Kevin
Bacon,” which you can read about at 'wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon'. This problem is challenging because it requires you to find the shortest path in a graph. You can read about shortest path algorithms at 'wikipedia.org/wiki/Shortest_path_problem'.
<IMG SRC="previous_motif.gif" ALT="Previous"> <IMG SRC="contents_motif.gif" ALT="Up"> <IMG SRC="next_motif.gif" ALT="Next">