← 学习库 Think Python 2e 目录

Chapter 15

> 来源: Think Python 2e (Allen B. Downey)

> 原页: https://greenteapress.com/thinkpython/html/thinkpython015.html

\

[插图缺失:thinkpython014.html]
[ [](thinkpython016.html)

------------------------------------------------------------------------

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 chapter 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:

pickle007

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 'w'00 method puts data into the file.

pickle009

Again, the file object keeps track of where it is, so if you call 'w'00 again, it adds the new data to the end.

pickle011

When you are done writing, you have to close the file.

pickle012

14.3   Format operator

The argument of 'w'00 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 'w':

pickle015

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, which contains one or more format sequences, which specify how the second operand is formatted. The result is a string.

For example, the format sequence 'w'0 means that the second operand should be formatted as an integer (% stands for “decimal”):

pickle021

The result is the string 'w'0, which is not to be confused with the integer value %0.

A format sequence can appear anywhere in the string, so you can embed a value in a sentence:

pickle024

If there is more than one format sequence in the string, the second argument has to be a tuple. Each format sequence is matched with an element of the tuple, in order.

The following example uses 'w'0 to format an integer, 'w'0 to format a floating-point number (don’t ask why), and 'w'0 to format a string:

pickle028

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:

pickle029

In the first example, there aren’t enough elements; in the second, the element is the wrong type.

The format operator is powerful, but it can be difficult to use. You can read more about it at pickle030.

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 %0 module provides functions for working with files and directories (“os” stands for “operating system”). pickle032 returns the name of the current directory:

pickle033

'w' stands for “current working directory.” The result in this example is pickle035, which is the home directory of a user named pickle03.

A string like 'w' 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 pickle038:

pickle039

pickle040 checks whether a file or directory exists:

pickle041

If it exists, pickle042 checks whether it’s a directory:

pickle043

Similarly, pickle044 checks whether it’s a file.

pickle045 returns a list of the files (and other directories) in the given directory:

pickle046

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.

pickle047

pickle048 takes a directory and a file name and joins them into a complete path.

Exercise 1  

The %0 module provides a function called 'w'0 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.

Solution: pickle051.

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 pickle0:

pickle053

If you don’t have permission to access a file:

pickle054

And if you try to open a directory for reading, you get

pickle055

To avoid these errors, you could use functions like pickle056 and pickle057, but it would take a lot of time and code to check all the possibilities (if “pickle05” 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 'w' statement does. The syntax is similar to an %0 statement:

pickle061

Python starts by executing the 'w' clause. If all goes well, it skips the pickle clause and proceeds. If an exception occurs, it jumps out of the 'w' clause and executes the pickle clause.

Handling an exception with a 'w' statement is called catching an exception. In this example, the pickle 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.

Exercise 2  

Write a function called 'w' that takes as arguments a pattern string, a replacement string, and two filenames; it should read the first file and write the contents into the second file (creating it if necessary). If the pattern string appears anywhere in the file, it should be replaced with the replacement string.

If an error occurs while opening, reading, writing or closing files, your program should catch the exception, print an error message, and exit. Solution: pickle069.

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 pickle 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:

pickle071

The mode 'w' 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, pickle updates the database file.

pickle074

When you access one of the items, pickle reads the file:

pickle076

If you make another assignment to an existing key, pickle replaces the old value:

pickle078

Many dictionary methods, like 'w'0 and 'w'00, also work with database objects. So does iteration with a 'w' statement.

pickle082

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

pickle083

14.7   Pickling

A limitation of pickle 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.

pickle086 takes an object as a parameter and returns a string representation ('w'00 is short for “dump string”):

pickle088

The format isn’t obvious to human readers; it is meant to be easy for pickle to interpret. pickle090 (“load string”) reconstitutes the object:

pickle091

Although the new object has the same value as the old, it is not (in general) the same object:

pickle092

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

Exercise 3  

If you download my solution to Exercise 4 from pickle095, you’ll see that it creates a dictionary that maps from a sorted string of letters to the list of words that can be spelled with those letters. For example, pickle maps to the list pickle097.

Write a module that imports pickle098 and provides two new functions: pickle099 should store the anagram dictionary in a “shelf;” pickle100 should look up a word and return a list of its anagrams. Solution: pickle101

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 %0, display the contents of a directory with %0, and launch a web browser by typing (for example) pickle1.

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

For example, the Unix command 'w'00 normally displays the contents of the current directory (in long format). You can launch %0 with pickle101:

pickle108

The argument is a string that contains a shell command. The return value is an object that behaves just like an open file. You can read the output from the %0 process one line at a time with pickle11 or get the whole thing at once with 'w'0:

pickle112

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

pickle113

The return value is the final status of the %0 process; 'w'0 means that it ended normally (with no errors).

For example, most Unix systems provide a command called pickle that reads the contents of a file and computes a “checksum.” You can read about MD5 at pickle117. This command provides an efficient way to check whether two files have the same contents. The probability that different contents yield the same checksum is very small (that is, unlikely to happen before the universe collapses).

You can use a pipe to run pickle from Python and get the result:

pickle119

Exercise 4  

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

  1. 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 'w'0). Hint: pickle1 provides several useful functions for manipulating file and path names.
  2. To recognize duplicates, you can use pickle to compute a “checksum” for each files. If two files have the same checksum, they probably have the same contents.
  3. To double-check, you can use the Unix command 'w'0.

Solution: pickle124.

14.9   Writing modules

Any file that contains Python code can be imported as a module. For example, suppose you have a file named 'w'00 with the following code:

pickle126

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:

pickle127

Now you have a module object %0:

pickle129

That provides a function called pickle130:

pickle131

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:

pickle132

pickle13 is a built-in variable that is set when the program starts. If the program is running as a script, pickle13 has the value pickle13; in that case, the test code is executed. Otherwise, if the module is being imported, the test code is skipped.

Exercise 5  

Type this example into a file named 'w'00 and run it as a script. Then run the Python interpreter and pickle137. What is the value of pickle13 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 pickle, 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:

pickle140

The built-in function 'w'0 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:

pickle142

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 %0. Others use a return character, represented %0. 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 pickle145. 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 %0, 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 'w' and pickle statements.

database:

A file whose contents are organized like a dictionary with keys that correspond to values.

14.12   Exercises

Exercise 6  

The pickle module provides methods for manipulating URLs and downloading information from the web. The following example downloads and prints a secret message from pickle151:

pickle152

Run this code and follow the instructions you see there. Solution: pickle153.


1

'w'00 is deprecated now, which means we are supposed to stop using it and start using the pickle155 module. But for simple cases, I find pickle156 more complicated than necessary. So I am going to keep using 'w'00 until they take it away.

Contribute

If you would like to make a contribution to support my books, you can use the button below. Thank you!

Pay what you want:

Small $1.00 USD Medium $5.00 USD Large $10.00 USD X-Large $20.00 USD XX-Large $50.00 USD

Are you using one of our books in a class?

We'd like to know about it. Please consider filling out this short survey.


------------------------------------------------------------------------

\

[插图缺失:thinkpython014.html]
[ [](thinkpython016.html)

---

← Chapter 14Chapter 16 →