Archive:Think Python/Files
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML> <HEAD>
<META http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <META name="GENERATOR" content="hevea 1.10"> <LINK rel="stylesheet" type="text/css" href="book.css"> <TITLE>Files</TITLE> </HEAD> <BODY > <A HREF="book014.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="book016.html"><IMG SRC="next_motif.gif" ALT="Next"></A>
<A NAME="htoc168">Chapter 14</A> Files
<A NAME="@default1229"></A> <A NAME="@default1230"></A>
<A NAME="toc153"></A><A NAME="htoc169">14.1</A> Persistence
<A NAME="@default1231"></A>
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.
<A NAME="@default1232"></A> <A NAME="@default1233"></A>
<A NAME="toc154"></A><A NAME="htoc170">14.2</A> Reading and writing
<A NAME="@default1234"></A>
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 <A HREF="book010.html#wordlist">9.1</A>.
<A NAME="@default1235"></A> <A NAME="@default1236"></A>
To write a file, you have to open it with mode
'w' as a second parameter:
<FONT COLOR=blue><FONT SIZE=4>>>> fout = open('output.txt', 'w')
>>> print fout
<open file 'output.txt', mode 'w' at 0xb7eb2410>
</FONT></FONT>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.
<FONT COLOR=blue><FONT SIZE=4>>>> line1 = "This here's the wattle,\n" >>> fout.write(line1) </FONT></FONT>
Again, the file object keeps track of where it is, so if you call write again, it adds the new data to the end.
<FONT COLOR=blue><FONT SIZE=4>>>> line2 = "the emblem of our land.\n" >>> fout.write(line2) </FONT></FONT>
When you are done writing, you have to close the file.
<FONT COLOR=blue><FONT SIZE=4>>>> fout.close() </FONT></FONT>
<A NAME="@default1237"></A> <A NAME="@default1238"></A>
<A NAME="toc155"></A><A NAME="htoc171">14.3</A> Format operator
<A NAME="@default1239"></A> <A NAME="@default1240"></A>
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:
<FONT COLOR=blue><FONT SIZE=4>>>> x = 52 >>> f.write(str(x)) </FONT></FONT>
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.
<A NAME="@default1241"></A>
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.
<A NAME="@default1242"></A>
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”):
<FONT COLOR=blue><FONT SIZE=4>>>> camels = 42 >>> '%d' % camels '42' </FONT></FONT>
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:
<FONT COLOR=blue><FONT SIZE=4>>>> camels = 42 >>> 'I have spotted %d camels.' % camels 'I have spotted 42 camels.' </FONT></FONT>
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:
<FONT COLOR=blue><FONT SIZE=4>>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels') 'In 3 years I have spotted 0.1 camels.' </FONT></FONT>
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:
<A NAME="@default1243"></A> <A NAME="@default1244"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> '%d %d %d' % (1, 2) TypeError: not enough arguments for format string >>> '%d' % 'dollars' TypeError: illegal argument type for built-in operation </FONT></FONT>
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.
<A NAME="toc156"></A><A NAME="htoc172">14.4</A> Filenames and paths
<A NAME="paths"></A>
<A NAME="@default1245"></A>
<A NAME="@default1246"></A> <A NAME="@default1247"></A>
<A NAME="@default1248"></A>
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.
<A NAME="@default1249"></A> <A NAME="@default1250"></A>
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:
<A NAME="@default1251"></A> <A NAME="@default1252"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> import os >>> cwd = os.getcwd() >>> print cwd /home/dinsdale </FONT></FONT>
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 NAME="@default1253"></A> <A NAME="@default1254"></A>
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.
<A NAME="@default1255"></A>
<A NAME="@default1256"></A> <A NAME="@default1257"></A>
<A NAME="@default1258"></A>
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:
<FONT COLOR=blue><FONT SIZE=4>>>> os.path.abspath('memo.txt')
'/home/dinsdale/memo.txt'
</FONT></FONT>os.path.exists checks whether a file or directory exists:
<A NAME="@default1259"></A> <A NAME="@default1260"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> os.path.exists('memo.txt')
True
</FONT></FONT>If it exists, os.path.isdir checks whether it’s a directory:
<FONT COLOR=blue><FONT SIZE=4>>>> os.path.isdir('memo.txt')
False
>>> os.path.isdir('music')
True
</FONT></FONT>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:
<FONT COLOR=blue><FONT SIZE=4>>>> os.listdir(cwd) ['music', 'photos', 'memo.txt'] </FONT></FONT>
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.
<A NAME="@default1261"></A> <A NAME="@default1262"></A>
<FONT COLOR=blue><FONT SIZE=4>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)
</FONT></FONT>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.
<A NAME="toc157"></A><A NAME="htoc173">14.5</A> Catching exceptions
<A NAME="catch"></A>
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:
<A NAME="@default1263"></A>
<A NAME="@default1264"></A> <A NAME="@default1265"></A>
<A NAME="@default1266"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> fin = open('bad_file')
IOError: [Errno 2] No such file or directory: 'bad_file'
</FONT></FONT>If you don’t have permission to access a file:
<A NAME="@default1267"></A> <A NAME="@default1268"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> fout = open('/etc/passwd', 'w')
IOError: [Errno 13] Permission denied: '/etc/passwd'
</FONT></FONT>And if you try to open a directory for reading, you get
<FONT COLOR=blue><FONT SIZE=4>>>> fin = open('/home')
IOError: [Errno 21] Is a directory
</FONT></FONT>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).
<A NAME="@default1269"></A>
<A NAME="@default1270"></A>
<A NAME="@default1271"></A>
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:
<FONT COLOR=blue><FONT SIZE=4>try:
fin = open('bad_file')
for line in fin:
print line
fin.close()
except:
print 'Something went wrong.'
</FONT></FONT>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.
<A NAME="toc158"></A><A NAME="htoc174">14.6</A> Databases
<A NAME="@default1272"></A>
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.
<A NAME="@default1273"></A> <A NAME="@default1274"></A>
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.
<A NAME="@default1275"></A> <A NAME="@default1276"></A>
Opening a database is similar to opening other files:
<FONT COLOR=blue><FONT SIZE=4>>>> import anydbm
>>> db = anydbm.open('captions.db', 'c')
</FONT></FONT>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.
<A NAME="@default1277"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> db['cleese.png'] = 'Photo of John Cleese.' </FONT></FONT>
When you access one of the items, anydbm reads the file:
<FONT COLOR=blue><FONT SIZE=4>>>> print db['cleese.png']Photo of John Cleese.
</FONT></FONT>
If you make another assignment to an existing key, anydbm replaces the old value:
<FONT COLOR=blue><FONT SIZE=4>>>> db['cleese.png'] = 'Photo of John Cleese doing a silly walk.' >>> print db['cleese.png'] Photo of John Cleese doing a silly walk. </FONT></FONT>
Many dictionary methods, like keys and items, also
work with database objects. So does iteration with a for
statement.
<A NAME="@default1278"></A>
<FONT COLOR=blue><FONT SIZE=4>for key in db:
print key
</FONT></FONT>As with other files, you should close the database when you are done:
<FONT COLOR=blue><FONT SIZE=4>>>> db.close() </FONT></FONT>
<A NAME="@default1279"></A> <A NAME="@default1280"></A>
<A NAME="toc159"></A><A NAME="htoc175">14.7</A> Pickling
<A NAME="@default1281"></A>
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.
<A NAME="@default1282"></A> <A NAME="@default1283"></A>
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”):
<FONT COLOR=blue><FONT SIZE=4>>>> import pickle >>> t = [1, 2, 3] >>> pickle.dumps(t) '(lp0\nI1\naI2\naI3\na.' </FONT></FONT>
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:
<FONT COLOR=blue><FONT SIZE=4>>>> t1 = [1, 2, 3] >>> s = pickle.dumps(t1) >>> t2 = pickle.loads(s) >>> print t2 [1, 2, 3] </FONT></FONT>
Although the new object has the same value as the old, it is not (in general) the same object:
<FONT COLOR=blue><FONT SIZE=4>>>> t == t2 True >>> t is t2 False </FONT></FONT>
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.
<A NAME="@default1284"></A> <A NAME="@default1285"></A>
<A NAME="@default1286"></A> <A NAME="@default1287"></A>
If you did Exercise <A HREF="book013.html#anagrams">12.4</A>, 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.
<A NAME="toc160"></A><A NAME="htoc176">14.8</A> Pipes
<A NAME="@default1288"></A> <A NAME="@default1289"></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 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.
<A NAME="@default1290"></A> <A NAME="@default1291"></A>
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:
<A NAME="@default1292"></A> <A NAME="@default1293"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> cmd = 'ls -l' >>> fp = os.popen(cmd) </FONT></FONT>
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:
<A NAME="@default1294"></A>
<A NAME="@default1295"></A> <A NAME="@default1296"></A>
<A NAME="@default1297"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> res = fp.read() </FONT></FONT>
When you are done, you close the pipe like a file:
<A NAME="@default1298"></A> <A NAME="@default1299"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> stat = fp.close() >>> print stat None </FONT></FONT>
The return value is the final status of the ls process; None means that it ended normally (with no errors).
<A NAME="@default1300"></A>
<A NAME="@default1301"></A> <A NAME="@default1302"></A>
<A NAME="@default1303"></A>
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:
<FONT COLOR=blue><FONT SIZE=4>def open_gzip(filename):
cmd = 'gunzip -c ' + filename
fp = os.popen(cmd)
return fp
</FONT></FONT>If you read lines from fp one at a time, you never have to store the uncompressed file in memory or on disk.
<A NAME="toc161"></A><A NAME="htoc177">14.9</A> Writing modules
<A NAME="modules"></A>
<A NAME="@default1304"></A> <A NAME="@default1305"></A>
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:
<FONT COLOR=blue><FONT SIZE=4>def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
print linecount('wc.py')
</FONT></FONT>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:
<FONT COLOR=blue><FONT SIZE=4>>>> import wc 7 </FONT></FONT>
Now you have a module object wc:
<A NAME="@default1306"></A> <A NAME="@default1307"></A>
<FONT COLOR=blue><FONT SIZE=4>>>> print wc <module 'wc' from 'wc.py'> </FONT></FONT>
That provides a function called linecount:
<FONT COLOR=blue><FONT SIZE=4>>>> wc.linecount('wc.py')
7
</FONT></FONT>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.
<A NAME="@default1308"></A> <A NAME="@default1309"></A>
Programs that will be imported as modules often use the following idiom:
<FONT COLOR=blue><FONT SIZE=4>if __name__ == '__main__':
print linecount('wc.py')
</FONT></FONT>__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__
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.
<A NAME="@default1310"></A>
<A NAME="@default1311"></A>
<A NAME="@default1312"></A>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.
<A NAME="toc162"></A><A NAME="htoc178">14.10</A> Debugging
<A NAME="@default1313"></A> <A NAME="@default1314"></A>
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:
<FONT COLOR=blue><FONT SIZE=4>>>> s = '1 2\t 3\n 4' >>> print s 1 2 3 4 </FONT></FONT>
<A NAME="@default1315"></A>
<A NAME="@default1316"></A>
<A NAME="@default1317"></A>
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:
<FONT COLOR=blue><FONT SIZE=4>>>> print repr(s) '1 2\t 3\n 4' </FONT></FONT>
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.
<A NAME="@default1318"></A>
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.
<A NAME="toc163"></A><A NAME="htoc179">14.11</A> Glossary
- persistent:
- Pertaining to a program that runs indefinitely
and keeps at least some of its data in permanent storage.
<A NAME="@default1319"></A> - 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. <A NAME="@default1320"></A> <A NAME="@default1321"></A>
- format string:
- A string, used with the format operator, that contains format sequences. <A NAME="@default1322"></A>
- format sequence:
- A sequence of characters in a format string, like %d, that specifies how a value should be formatted. <A NAME="@default1323"></A>
- text file:
- A sequence of characters stored in permanent storage like a hard drive. <A NAME="@default1324"></A>
- directory:
- A named collection of files, also called a folder. <A NAME="@default1325"></A>
- path:
- A string that identifies a file. <A NAME="@default1326"></A>
- relative path:
- A path that starts from the current directory. <A NAME="@default1327"></A>
- absolute path:
- A path that starts from the topmost directory in the file system. <A NAME="@default1328"></A>
- catch:
- To prevent an exception from terminating a program using the try and except statements. <A NAME="@default1329"></A>
- database:
- A file whose contents are organized like a dictionary with keys that correspond to values. <A NAME="@default1330"></A>
<A NAME="toc164"></A><A NAME="htoc180">14.12</A> Exercises
<A NAME="@default1331"></A> <A NAME="@default1332"></A> <A NAME="@default1333"></A>
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:<EM><FONT COLOR=blue><FONT SIZE=4>import urllib
conn = urllib.urlopen('http://thinkpython.com/secret.html')
for line in conn.fp:
print line.strip()
</FONT></FONT></EM>Run this code and follow the instructions you see there.
<A NAME="@default1334"></A> <A NAME="@default1335"></A>
<A NAME="@default1336"></A>
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.<A NAME="@default1337"></A> <A NAME="@default1338"></A> <A NAME="@default1339"></A> <A NAME="@default1340"></A>
- 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.
<A NAME="@default1341"></A>
<A NAME="@default1342"></A>
<A NAME="@default1343"></A>
<A NAME="@default1344"></A>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.<A NAME="@default1345"></A>
<A NAME="@default1346"></A>
<A NAME="@default1347"></A>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
<EM><FONT COLOR=blue><FONT SIZE=4>import imdb
def print_info(actor, date, title, role):
print actor, date, title, role
imdb.process_file('actors.list.gz', print_info)
</FONT></FONT></EM>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
- 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.
<A NAME="@default1348"></A> <A NAME="@default1349"></A>
- 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.<A NAME="@default1350"></A> <A NAME="@default1351"></A>
- 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.
<A HREF="book014.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="book016.html"><IMG SRC="next_motif.gif" ALT="Next"></A> </BODY> </HTML>