Think Python/Files

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.

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&#XA0;9.1.

To write a file, you have to open it with mode as a second parameter: 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&#X2019;t exist, a new one is created.

The write method puts data into the file. Again, the file object keeps track of where it is, so if you call write again, it adds the new data to the end. When you are done writing, you have to close the file.

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: 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  means that the first expression in the tuple should be formatted as an integer (<TT>d</TT> stands for &#X201C;decimal&#X201D;): The result is the string, which is not to be confused 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: The format sequence  formats the next element in the tuple as a floating-point number (don&#X2019;t ask why), and  formats the next item as a string: 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:

In the first example, there aren&#X2019;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 <TT>docs.python.org/lib/typesseq-strings.html</TT>.

Filenames and paths
Files are organized into directories (also called &#X201C;folders&#X201D;). Every running program has a &#X201C;current directory,&#X201D; 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 <TT>os</TT> module provides functions for working with files and directories (&#X201C;os&#X201D; stands for &#X201C;operating system&#X201D;). <TT>os.getcwd</TT> returns the name of the current directory:

<TT>cwd</TT> stands for &#X201C;current working directory.&#X201D; The result in this example is <TT>/home/dinsdale</TT>, which is the home directory of a user named <TT>dinsdale</TT>.

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 a file, you can use <TT>os.path.abspath</TT>: <TT>os.path.exists</TT> checks whether a file or directory exists:

If it exists, <TT>os.path.isdir</TT> checks whether it&#X2019;s a directory: Similarly, <TT>os.path.isfile</TT> checks whether it&#X2019;s a file.

<TT>os.listdir</TT> returns a list of the files (and other directories) in the given directory: To demonstrate these functions, the following example &#X201C;walks&#X201D; through a directory, prints the names of all the files, and calls itself recursively on all the directories.

<TT>os.path.join</TT> takes a directory and a file name and joins them into a complete path.

Exercise 1
Modify '<TT>walk</TT>' so that instead of printing the names of the files, it returns a list of names.

Exercise 2
''The '<TT>os</TT>' module provides a function called '<TT>walk</TT>' 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.''

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&#X2019;t exist, you get an <TT>IOError</TT>:

If you don&#X2019;t have permission to access a file:

And if you try to open a directory for reading, you get To avoid these errors, you could use functions like <TT>os.path.exists</TT> and <TT>os.path.isfile</TT>, but it would take a lot of time and code to check all the possibilities (if &#X201C;<TT>Errno 21</TT>&#X201D; 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 <TT>try</TT> statement does. The syntax is similar to an <TT>if</TT> statement: Python starts by executing the <TT>try</TT> clause. If all goes well, it skips the <TT>except</TT> clause and proceeds. If an 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, catching an exception gives you a chance to fix the problem, or try again, or at least end the program gracefully.

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 <TT>anydbm</TT> provides an interface for creating and updating database files. As an example, I&#X2019;ll create a database that contains captions for image files.

Opening a database is similar to opening other files: The mode  means that the database should be created if it doesn&#X2019;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, <TT>anydbm</TT> updates the database file.

When you access one of the items, <TT>anydbm</TT> reads the file: If you make another assignment to an existing key, <TT>anydbm</TT> replaces the old value: Many dictionary methods, like <TT>keys</TT> and <TT>items</TT>, also work with database objects. So does iteration with a <TT>for</TT> statement.

As with other files, you should close the database when you are done:

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 error.

The <TT>pickle</TT> 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.

<TT>pickle.dumps</TT> takes an object as a parameter and returns a string representation (<TT>dumps</TT> is short for &#X201C;dump string&#X201D;): The format isn&#X2019;t obvious to human readers; it is meant to be easy for <TT>pickle</TT> to interpret. <TT>pickle.loads</TT> (&#X201C;load string&#X201D;) reconstitutes the object: Although the new object has the same value as the old, it is not (in general) the same 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 encapsulated in a module called <TT>shelve</TT>.

<DIV CLASS="theorem">Exercise&#XA0;3&#XA0;&#XA0;

If you did Exercise&#XA0;'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.</DIV>

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 <TT>cd</TT>, display the contents of a directory with <TT>ls</TT>, and launch a web browser by typing (for example) <TT>Firefox</TT>.

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 launch <TT>ls</TT> with <TT>os.popen</TT>:

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 <TT>ls</TT> process one line at a time with <TT>readline</TT> or get the whole thing at once with <TT>read</TT>:

When you are done, you close the pipe like a file:

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 following function takes the name of a compressed file as a parameter and returns a pipe that uses <TT>gzip</TT> to decompress the contents: 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.

Writing modules
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: 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: Now you have a module object <TT>wc</TT>:

That provides a function called : So that&#X2019;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&#X2019;t execute them.

Programs that will be imported as modules often use the following idiom: is a built-in variable that is set when the program starts. If the program is running as a script, has the value ; in that case, the test code is executed. Otherwise, if the module is being imported, the test code is skipped.

<DIV CLASS="theorem">Exercise&#XA0;4&#XA0;&#XA0;'' Type this example into a file named '<TT>wc.py</TT>' and run it as a script. Then run the Python interpreter and '<TT>import wc</TT>'. What is the value of   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 '<TT>reload</TT>', but it can be tricky, so the safest thing to do is restart the interpreter and then import the module again. </DIV>

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:

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 strings, it represents whitespace characters with backslash sequences: 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. Others use a return character, represented. 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 <TT>wikipedia.org/wiki/Newline</TT>. Or, of course, you could write one yourself.

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. </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 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. </DD><DT CLASS="dt-description">format sequence:</DT><DD CLASS="dd-description"> A sequence of characters in a format string, 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. </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. </DD><DT CLASS="dt-description">catch:</DT><DD CLASS="dd-description"> To prevent an exception from terminating a program using the <TT>try</TT> 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. </DD></DL>

Exercises
<DIV CLASS="theorem">Exercise&#XA0;5&#XA0;&#XA0;''The '<TT>urllib</TT>' module provides methods for manipulating URLs and downloading information from the web. The following example downloads and prints a secret message from '<TT>thinkpython.com</TT>':''

Run this code and follow the instructions you see there.

</DIV><DIV CLASS="theorem">Exercise&#XA0;6&#XA0;&#XA0;''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 '<TT>.mp3</TT>'). Hint: '<TT>os.path</TT>' 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 &#X201C;message&#X201D; and returns a 128-bit &#X201C;checksum.&#X201D; The probability is very small that two files with different contents will return the same checksum.

''You can read about MD5 at '<TT>wikipedia.org/wiki/Md5</TT>'. On a Unix system you can use the program '<TT>md5sum</TT>' and a pipe to compute checksums from Python.'' </DIV> <DIV CLASS="theorem">Exercise&#XA0;7&#XA0;&#XA0;''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 '<TT>actors.list.gz</TT>' and '<TT>actresses.list.gz</TT>'; you 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 download it from '<TT>thinkpython.com/code/imdb.py</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   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:''

When you call  , it opens '<TT>filename</TT>', reads the contents, and calls  '' once for each line in the file.   takes an actor, date, movie title and role as 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 &#X201C;costars&#X201D; 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 &#X201C;Six Degrees of Kevin Bacon,&#X201D; 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 path in a graph. You can read about shortest path algorithms at '<TT>wikipedia.org/wiki/Shortest_path_problem</TT>'.

</DIV>