forked from bailiangrui/git-basics-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththinkpython2015.html
More file actions
588 lines (558 loc) · 40.5 KB
/
thinkpython2015.html
File metadata and controls
588 lines (558 loc) · 40.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<meta name="generator" content="hevea 2.09">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="thinkpython2.css">
<title>Files</title>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><strong>Think Python</strong> - How to Think like a Computer Scientist (2e) <em>by Allen B. Downey</em></a>
</div>
<div>
<ul class="nav navbar-nav navbar-right">
<li><a href="http://greenteapress.com/thinkpython2/html/index.html"><span class="glyphicon glyphicon glyphicon-book" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2014.html"><span class="glyphicon glyphicon glyphicon-menu-left" aria-hidden="true"></span></a></li>
<li><a href="index.html"><span class="glyphicon glyphicon glyphicon-home" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2016.html"><span class="glyphicon glyphicon glyphicon-menu-right" aria-hidden="true"></span></a></li>
<li><a href="http://amzn.to/1VUYQUU"><span class="glyphicon glyphicon glyphicon-shopping-cart" aria-hidden="true"></span></a></li>
</ul>
<div>
</div><!-- /.container-fluid -->
</nav>
<table>
<tr>
<td valign="top" width="100" bgcolor="#b6459a" id="col-left">
</td>
<td valign="top" id="content">
<p>
<h1 class="chapter" id="sec164">Chapter 14  Files</h1>
<p>This chapter introduces the idea of “persistent” programs that
keep data in permanent storage, and shows how to use different
kinds of permanent storage, like files and databases.</p>
<h2 class="section" id="sec165">14.1  Persistence</h2>
<p>
<a id="hevea_default1206"></a>
<a id="hevea_default1207"></a>
<a id="hevea_default1208"></a></p><p>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.</p><p>Other programs are <span class="c010">persistent</span>: 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.</p><p>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.</p><p>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.</p><p>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,
<span class="c004">pickle</span>, that makes it easy to store program data.
<a id="hevea_default1209"></a>
<a id="hevea_default1210"></a></p>
<h2 class="section" id="sec166">14.2  Reading and writing</h2>
<p>
<a id="hevea_default1211"></a></p><p>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="thinkpython2010.html#wordlist">9.1</a>.
<a id="hevea_default1212"></a>
<a id="hevea_default1213"></a></p><p>To write a file, you have to open it with mode <code>'w'</code> as a second
parameter:</p><pre class="verbatim">>>> fout = open('output.txt', 'w')
</pre><p>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.</p><p><span class="c004">open</span> returns a file object that provides methods for working
with the file.
The <span class="c004">write</span> method puts data into the file.</p><pre class="verbatim">>>> line1 = "This here's the wattle,\n"
>>> fout.write(line1)
24
</pre><p>The return value is the number of characters that were written.
The file object keeps track of where it is, so if
you call <span class="c004">write</span> again, it adds the new data to the end of
the file.</p><pre class="verbatim">>>> line2 = "the emblem of our land.\n"
>>> fout.write(line2)
24
</pre><p>When you are done writing, you should close the file.</p><pre class="verbatim">>>> fout.close()
</pre><p><a id="hevea_default1214"></a>
<a id="hevea_default1215"></a>
If you don’t close the file, it gets closed for you when the
program ends.</p>
<h2 class="section" id="sec167">14.3  Format operator</h2>
<p>
<a id="hevea_default1216"></a>
<a id="hevea_default1217"></a></p><p>The argument of <span class="c004">write</span> 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 <span class="c004">str</span>:</p><pre class="verbatim">>>> x = 52
>>> fout.write(str(x))
</pre><p>An alternative is to use the <span class="c010">format operator</span>, <span class="c004">%</span>. When
applied to integers, <span class="c004">%</span> is the modulus operator. But
when the first operand is a string, <span class="c004">%</span> is the format operator.
<a id="hevea_default1218"></a></p><p>The first operand is the <span class="c010">format string</span>, which contains
one or more <span class="c010">format sequences</span>, which
specify how
the second operand is formatted. The result is a string.
<a id="hevea_default1219"></a></p><p>For example, the format sequence <code>'%d'</code> means that
the second operand should be formatted as a decimal
integer:</p><pre class="verbatim">>>> camels = 42
>>> '%d' % camels
'42'
</pre><p>The result is the string <code>'42'</code>, which is not to be confused
with the integer value <span class="c004">42</span>.</p><p>A format sequence can appear anywhere in the string,
so you can embed a value in a sentence:</p><pre class="verbatim">>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
</pre><p>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.</p><p>The following example uses <code>'%d'</code> to format an integer,
<code>'%g'</code> to format a floating-point number, and
<code>'%s'</code> to format a string:</p><pre class="verbatim">>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'
</pre><p>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 id="hevea_default1220"></a>
<a id="hevea_default1221"></a></p><pre class="verbatim">>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: %d format: a number is required, not str
</pre><p>In the first example, there aren’t enough elements; in the
second, the element is the wrong type.</p><p>For more information on the format operator, see
<a href="https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting"><span class="c004">https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting</span></a>. A more powerful alternative is the string
format method, which you can read about at
<a href="https://docs.python.org/3/library/stdtypes.html#str.format"><span class="c004">https://docs.python.org/3/library/stdtypes.html#str.format</span></a>.</p>
<h2 class="section" id="sec168">14.4  Filenames and paths</h2>
<p>
<a id="paths"></a>
<a id="hevea_default1222"></a>
<a id="hevea_default1223"></a>
<a id="hevea_default1224"></a>
<a id="hevea_default1225"></a></p><p>Files are organized into <span class="c010">directories</span> (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 id="hevea_default1226"></a>
<a id="hevea_default1227"></a></p><p>The <span class="c004">os</span> module provides functions for working with files and
directories (“os” stands for “operating system”). <span class="c004">os.getcwd</span>
returns the name of the current directory:
<a id="hevea_default1228"></a>
<a id="hevea_default1229"></a></p><pre class="verbatim">>>> import os
>>> cwd = os.getcwd()
>>> cwd
'/home/dinsdale'
</pre><p><span class="c004">cwd</span> stands for “current working directory”. The result in
this example is <span class="c004">/home/dinsdale</span>, which is the home directory of a
user named <span class="c004">dinsdale</span>.
<a id="hevea_default1230"></a>
<a id="hevea_default1231"></a></p><p>A string like <code>'/home/dinsdale'</code> that identifies a file or
directory is called a <span class="c010">path</span>.</p><p>A simple filename, like <span class="c004">memo.txt</span> is also considered a path,
but it is a <span class="c010">relative path</span> because it relates to the current
directory. If the current directory is <span class="c004">/home/dinsdale</span>, the
filename <span class="c004">memo.txt</span> would refer to <span class="c004">/home/dinsdale/memo.txt</span>.
<a id="hevea_default1232"></a> <a id="hevea_default1233"></a>
<a id="hevea_default1234"></a> <a id="hevea_default1235"></a></p><p>A path that begins with <span class="c004">/</span> does not depend on the current
directory; it is called an <span class="c010">absolute path</span>. To find the absolute
path to a file, you can use <span class="c004">os.path.abspath</span>:</p><pre class="verbatim">>>> os.path.abspath('memo.txt')
'/home/dinsdale/memo.txt'
</pre><p><span class="c004">os.path</span> provides other functions for working with filenames
and paths. For example,
<span class="c004">os.path.exists</span> checks
whether a file or directory exists:
<a id="hevea_default1236"></a>
<a id="hevea_default1237"></a></p><pre class="verbatim">>>> os.path.exists('memo.txt')
True
</pre><p>If it exists, <span class="c004">os.path.isdir</span> checks whether it’s a directory:</p><pre class="verbatim">>>> os.path.isdir('memo.txt')
False
>>> os.path.isdir('/home/dinsdale')
True
</pre><p>Similarly, <span class="c004">os.path.isfile</span> checks whether it’s a file.</p><p><span class="c004">os.listdir</span> returns a list of the files (and other directories)
in the given directory:</p><pre class="verbatim">>>> os.listdir(cwd)
['music', 'photos', 'memo.txt']
</pre><p>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 id="hevea_default1238"></a>
<a id="hevea_default1239"></a></p><pre class="verbatim">def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
if os.path.isfile(path):
print(path)
else:
walk(path)
</pre><p><span class="c004">os.path.join</span> takes a directory and a file name and joins
them into a complete path. </p><p>The <span class="c004">os</span> module provides a function called <span class="c004">walk</span> that is
similar to this one but more versatile. As an exercise, read the
documentation and use it to print the names of the files in a given
directory and its subdirectories. You can download my solution from
<a href="http://thinkpython2.com/code/walk.py"><span class="c004">http://thinkpython2.com/code/walk.py</span></a>.</p>
<h2 class="section" id="sec169">14.5  Catching exceptions</h2>
<p>
<a id="catch"></a></p><p>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
<span class="c004">IOError</span>:
<a id="hevea_default1240"></a>
<a id="hevea_default1241"></a>
<a id="hevea_default1242"></a>
<a id="hevea_default1243"></a></p><pre class="verbatim">>>> fin = open('bad_file')
IOError: [Errno 2] No such file or directory: 'bad_file'
</pre><p>If you don’t have permission to access a file:
<a id="hevea_default1244"></a>
<a id="hevea_default1245"></a></p><pre class="verbatim">>>> fout = open('/etc/passwd', 'w')
PermissionError: [Errno 13] Permission denied: '/etc/passwd'
</pre><p>And if you try to open a directory for reading, you get</p><pre class="verbatim">>>> fin = open('/home')
IsADirectoryError: [Errno 21] Is a directory: '/home'
</pre><p>To avoid these errors, you could use functions like <span class="c004">os.path.exists</span>
and <span class="c004">os.path.isfile</span>, but it would take a lot of time and code
to check all the possibilities (if “<span class="c004">Errno 21</span>” is any
indication, there are at least 21 things that can go wrong).
<a id="hevea_default1246"></a>
<a id="hevea_default1247"></a>
<a id="hevea_default1248"></a></p><p>It is better to go ahead and try—and deal with problems if they
happen—which is exactly what the <span class="c004">try</span> statement does. The
syntax is similar to an <span class="c004">if...else</span> statement:</p><pre class="verbatim">try:
fin = open('bad_file')
except:
print('Something went wrong.')
</pre><p>Python starts by executing the <span class="c004">try</span> clause. If all goes
well, it skips the <span class="c004">except</span> clause and proceeds. If an
exception occurs, it jumps out of the <span class="c004">try</span> clause and
runs the <span class="c004">except</span> clause.</p><p>Handling an exception with a <span class="c004">try</span> statement is called <span class="c010">catching</span> an exception. In this example, the <span class="c004">except</span> 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.</p>
<h2 class="section" id="sec170">14.6  Databases</h2>
<p>
<a id="hevea_default1249"></a></p><p>A <span class="c010">database</span> is a file that is organized for storing data. Many
databases are organized like a dictionary in the sense that they map
from keys to values. The biggest difference between a database and a
dictionary is that the database is on disk (or other permanent
storage), so it persists after the program ends. <a id="hevea_default1250"></a> <a id="hevea_default1251"></a></p><p>The module <span class="c004">dbm</span> provides an interface for creating
and updating database files.
As an example, I’ll create a database
that contains captions for image files.
<a id="hevea_default1252"></a>
<a id="hevea_default1253"></a></p><p>Opening a database is similar to opening other files:</p><pre class="verbatim">>>> import dbm
>>> db = dbm.open('captions', 'c')
</pre><p>The mode <code>'c'</code> 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.
<a id="hevea_default1254"></a>
<a id="hevea_default1255"></a></p><p>When you create a new item, <span class="c004">dbm</span> updates the database file.
<a id="hevea_default1256"></a></p><pre class="verbatim">>>> db['cleese.png'] = 'Photo of John Cleese.'
</pre><p>When you access one of the items, <span class="c004">dbm</span> reads the file:</p><pre class="verbatim">>>> db['cleese.png']
b'Photo of John Cleese.'
</pre><p>The result is a <span class="c010">bytes object</span>, which is why it begins with <span class="c004">b</span>. A bytes object is similar to a string in many ways. When you
get farther into Python, the difference becomes important, but for now
we can ignore it.
<a id="hevea_default1257"></a>
<a id="hevea_default1258"></a></p><p>If you make another assignment to an existing key, <span class="c004">dbm</span> replaces
the old value:</p><pre class="verbatim">>>> db['cleese.png'] = 'Photo of John Cleese doing a silly walk.'
>>> db['cleese.png']
b'Photo of John Cleese doing a silly walk.'
</pre><p>Some dictionary methods, like <span class="c004">keys</span> and <span class="c004">items</span>, don’t
work with database objects. But iteration with a <span class="c004">for</span>
loop works:
<a id="hevea_default1259"></a></p><pre class="verbatim">for key in db:
print(key, db[key])
</pre><p>As with other files, you should close the database when you are
done:</p><pre class="verbatim">>>> db.close()
</pre><p><a id="hevea_default1260"></a>
<a id="hevea_default1261"></a></p>
<h2 class="section" id="sec171">14.7  Pickling</h2>
<p>
<a id="hevea_default1262"></a></p><p>A limitation of <span class="c004">dbm</span> is that the keys and values have to be
strings or bytes. If you try to use any other type, you get an error.
<a id="hevea_default1263"></a> <a id="hevea_default1264"></a></p><p>The <span class="c004">pickle</span> 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.</p><p><span class="c004">pickle.dumps</span> takes an object as a parameter and returns
a string representation (<span class="c004">dumps</span> is short for “dump string”):</p><pre class="verbatim">>>> import pickle
>>> t = [1, 2, 3]
>>> pickle.dumps(t)
b'\x80\x03]q\x00(K\x01K\x02K\x03e.'
</pre><p>The format isn’t obvious to human readers; it is meant to be
easy for <span class="c004">pickle</span> to interpret. <span class="c004">pickle.loads</span>
(“load string”) reconstitutes the object:</p><pre class="verbatim">>>> t1 = [1, 2, 3]
>>> s = pickle.dumps(t1)
>>> t2 = pickle.loads(s)
>>> t2
[1, 2, 3]
</pre><p>Although the new object has the same value as the old, it is
not (in general) the same object:</p><pre class="verbatim">>>> t1 == t2
True
>>> t1 is t2
False
</pre><p>In other words, pickling and then unpickling has the same effect
as copying the object.</p><p>You can use <span class="c004">pickle</span> to store non-strings in a database.
In fact, this combination is so common that it has been
encapsulated in a module called <span class="c004">shelve</span>.
<a id="hevea_default1265"></a>
<a id="hevea_default1266"></a></p>
<h2 class="section" id="sec172">14.8  Pipes</h2>
<p>
<a id="hevea_default1267"></a>
<a id="hevea_default1268"></a></p><p>Most operating systems provide a command-line interface,
also known as a <span class="c010">shell</span>. Shells usually provide commands
to navigate the file system and launch applications. For
example, in Unix you can change directories with <span class="c004">cd</span>,
display the contents of a directory with <span class="c004">ls</span>, and launch
a web browser by typing (for example) <span class="c004">firefox</span>.
<a id="hevea_default1269"></a>
<a id="hevea_default1270"></a></p><p>Any program that you can launch from the shell can also be
launched from Python using a <span class="c010">pipe object</span>, which
represents a running program.</p><p>For example, the Unix command <span class="c004">ls -l</span> normally displays the
contents of the current directory in long format. You can
launch <span class="c004">ls</span> with <span class="c004">os.popen</span><sup><a id="text1" href="thinkpython2015.html#note1">1</a></sup>:
<a id="hevea_default1271"></a>
<a id="hevea_default1272"></a></p><pre class="verbatim">>>> cmd = 'ls -l'
>>> fp = os.popen(cmd)
</pre><p>The argument is a string that contains a shell command. The
return value is an object that behaves like an open
file. You can read the output from the <span class="c004">ls</span> process one
line at a time with <span class="c004">readline</span> or get the whole thing at
once with <span class="c004">read</span>:
<a id="hevea_default1273"></a>
<a id="hevea_default1274"></a>
<a id="hevea_default1275"></a>
<a id="hevea_default1276"></a></p><pre class="verbatim">>>> res = fp.read()
</pre><p>When you are done, you close the pipe like a file:
<a id="hevea_default1277"></a>
<a id="hevea_default1278"></a></p><pre class="verbatim">>>> stat = fp.close()
>>> print(stat)
None
</pre><p>The return value is the final status of the <span class="c004">ls</span> process;
<span class="c004">None</span> means that it ended normally (with no errors).</p><p>For example, most Unix systems provide a command called <span class="c004">md5sum</span>
that reads the contents of a file and computes a “checksum”.
You can read about MD5 at <a href="http://en.wikipedia.org/wiki/Md5"><span class="c004">http://en.wikipedia.org/wiki/Md5</span></a>. 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).
<a id="hevea_default1279"></a>
<a id="hevea_default1280"></a></p><p>You can use a pipe to run <span class="c004">md5sum</span> from Python and get the result:</p><pre class="verbatim">>>> filename = 'book.tex'
>>> cmd = 'md5sum ' + filename
>>> fp = os.popen(cmd)
>>> res = fp.read()
>>> stat = fp.close()
>>> print(res)
1e0033f0ed0656636de0d75144ba32e0 book.tex
>>> print(stat)
None
</pre>
<h2 class="section" id="sec173">14.9  Writing modules</h2>
<p>
<a id="modules"></a>
<a id="hevea_default1281"></a>
<a id="hevea_default1282"></a></p><p>Any file that contains Python code can be imported as a module.
For example, suppose you have a file named <span class="c004">wc.py</span> with the following
code:</p><pre class="verbatim">def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
print(linecount('wc.py'))
</pre><p>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:</p><pre class="verbatim">>>> import wc
7
</pre><p>Now you have a module object <span class="c004">wc</span>:
<a id="hevea_default1283"></a>
<a id="hevea_default1284"></a></p><pre class="verbatim">>>> wc
<module 'wc' from 'wc.py'>
</pre><p>The module object provides <code>linecount</code>:</p><pre class="verbatim">>>> wc.linecount('wc.py')
7
</pre><p>So that’s how you write modules in Python.</p><p>The only problem with this example is that when you import
the module it runs the test code at the bottom. Normally
when you import a module, it defines new functions but it
doesn’t run them.
<a id="hevea_default1285"></a>
<a id="hevea_default1286"></a></p><p>Programs that will be imported as modules often
use the following idiom:</p><pre class="verbatim">if __name__ == '__main__':
print(linecount('wc.py'))
</pre><p><code>__name__</code> is a built-in variable that is set when the
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 runs. Otherwise,
if the module is being imported, the test code is skipped.</p><p>As an exercise, type this example into a file named <span class="c004">wc.py</span> and run
it as a script. Then run the Python interpreter and
<span class="c004">import wc</span>. What is the value of <code>__name__</code>
when the module is being imported?</p><p>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 id="hevea_default1287"></a>
<a id="hevea_default1288"></a>
<a id="hevea_default1289"></a></p><p>If you want to reload a module, you can use the built-in function
<span class="c004">reload</span>, but it can be tricky, so the safest thing to do is
restart the interpreter and then import the module again.</p>
<h2 class="section" id="sec174">14.10  Debugging</h2>
<p>
<a id="hevea_default1290"></a>
<a id="hevea_default1291"></a></p><p>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:</p><pre class="verbatim">>>> s = '1 2\t 3\n 4'
>>> print(s)
1 2 3
4
</pre><p><a id="hevea_default1292"></a>
<a id="hevea_default1293"></a>
<a id="hevea_default1294"></a></p><p>The built-in function <span class="c004">repr</span> 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:</p><pre class="verbatim">>>> print(repr(s))
'1 2\t 3\n 4'
</pre><p>This can be helpful for debugging.</p><p>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 <code>\n</code>. Others use
a return character, represented <code>\r</code>. Some use both.
If you move files between different systems, these inconsistencies
can cause problems.
<a id="hevea_default1295"></a></p><p>For most systems, there are applications to convert from one
format to another. You can find them (and read more about this
issue) at <a href="http://en.wikipedia.org/wiki/Newline"><span class="c004">http://en.wikipedia.org/wiki/Newline</span></a>. Or, of course, you
could write one yourself.</p>
<h2 class="section" id="sec175">14.11  Glossary</h2>
<dl class="description"><dt class="dt-description"><span class="c010">persistent:</span></dt><dd class="dd-description"> Pertaining to a program that runs indefinitely
and keeps at least some of its data in permanent storage.
<a id="hevea_default1296"></a></dd><dt class="dt-description"><span class="c010">format operator:</span></dt><dd class="dd-description"> An operator, <span class="c004">%</span>, 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 id="hevea_default1297"></a>
<a id="hevea_default1298"></a></dd><dt class="dt-description"><span class="c010">format string:</span></dt><dd class="dd-description"> A string, used with the format operator, that
contains format sequences.
<a id="hevea_default1299"></a></dd><dt class="dt-description"><span class="c010">format sequence:</span></dt><dd class="dd-description"> A sequence of characters in a format string,
like <span class="c004">%d</span>, that specifies how a value should be formatted.
<a id="hevea_default1300"></a></dd><dt class="dt-description"><span class="c010">text file:</span></dt><dd class="dd-description"> A sequence of characters stored in permanent
storage like a hard drive.
<a id="hevea_default1301"></a></dd><dt class="dt-description"><span class="c010">directory:</span></dt><dd class="dd-description"> A named collection of files, also called a folder.
<a id="hevea_default1302"></a></dd><dt class="dt-description"><span class="c010">path:</span></dt><dd class="dd-description"> A string that identifies a file.
<a id="hevea_default1303"></a></dd><dt class="dt-description"><span class="c010">relative path:</span></dt><dd class="dd-description"> A path that starts from the current directory.
<a id="hevea_default1304"></a></dd><dt class="dt-description"><span class="c010">absolute path:</span></dt><dd class="dd-description"> A path that starts from the topmost directory
in the file system.
<a id="hevea_default1305"></a></dd><dt class="dt-description"><span class="c010">catch:</span></dt><dd class="dd-description"> To prevent an exception from terminating
a program using the <span class="c004">try</span>
and <span class="c004">except</span> statements.
<a id="hevea_default1306"></a></dd><dt class="dt-description"><span class="c010">database:</span></dt><dd class="dd-description"> A file whose contents are organized like a dictionary
with keys that correspond to values.
<a id="hevea_default1307"></a></dd><dt class="dt-description"><span class="c010">bytes object:</span></dt><dd class="dd-description"> An object similar to a string.
<a id="hevea_default1308"></a>
<a id="hevea_default1309"></a></dd><dt class="dt-description"><span class="c010">shell:</span></dt><dd class="dd-description"> A program that allows users to type commands and then
executes them by starting other programs.
<a id="hevea_default1310"></a></dd><dt class="dt-description"><span class="c010">pipe object:</span></dt><dd class="dd-description"> An object that represents a running program, allowing
a Python program to run commands and read the results.
<a id="hevea_default1311"></a>
<a id="hevea_default1312"></a></dd></dl>
<h2 class="section" id="sec176">14.12  Exercises</h2>
<div class="theorem"><span class="c010">Exercise 1</span>  <p><em>Write a function called <span class="c004">sed</span> 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.</em></p><p><em>If an error occurs while opening, reading, writing or closing files,
your program should catch the exception, print an error message, and
exit. Solution: </em><a href="http://thinkpython2.com/code/sed.py"><em><span class="c004">http://thinkpython2.com/code/sed.py</span></em></a><em>.</em></p></div><div class="theorem"><span class="c010">Exercise 2</span>  
<a id="hevea_default1313"></a>
<a id="hevea_default1314"></a><p><em>If you download my solution to Exercise </em><a href="thinkpython2013.html#anagrams"><em>2</em></a><em> from
</em><a href="http://thinkpython2.com/code/anagram_sets.py"><span class="c004"><em>http://thinkpython2.com/code/anagram_sets.py</em></span></a><em>, 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,
<code>'opst'</code> maps to the list
<code>['opts', 'post', 'pots', 'spot', 'stop', 'tops']</code>.</em></p><p><em>Write a module that imports <code>anagram_sets</code> and provides
two new functions: <code>store_anagrams</code> should store the
anagram dictionary in a “shelf”; <code>read_anagrams</code> should
look up a word and return a list of its anagrams.
Solution: </em><a href="http://thinkpython2.com/code/anagram_db.py"><span class="c004"><em>http://thinkpython2.com/code/anagram_db.py</em></span></a><em>.</em></p></div><div class="theorem"><span class="c010">Exercise 3</span>  
<a id="checksum"></a>
<a id="hevea_default1315"></a><p><em>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.</em></p><ol class="enumerate" type=1><li class="li-enumerate"><em>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 <span class="c004">.mp3</span>).
Hint: <span class="c004">os.path</span> provides several useful functions for
manipulating file and path names.
</em><a id="hevea_default1316"></a>
<a id="hevea_default1317"></a>
<a id="hevea_default1318"></a>
<a id="hevea_default1319"></a></li><li class="li-enumerate"><em>To recognize duplicates, you can use <span class="c004">md5sum</span>
to compute a “checksum” for each files. If two files have
the same checksum, they probably have the same contents.
</em><a id="hevea_default1320"></a></li><li class="li-enumerate"><em>To double-check, you can use the Unix command <span class="c004">diff</span>.
</em><a id="hevea_default1321"></a></li></ol><p><em>Solution: </em><a href="http://thinkpython2.com/code/find_duplicates.py"><em><span class="c004">http://thinkpython2.com/code/find_duplicates.py</span></em></a><em>.</em></p></div>
<hr class="footnoterule"><dl class="thefootnotes"><dt class="dt-thefootnotes">
<a id="note1" href="thinkpython2015.html#text1">1</a></dt><dd class="dd-thefootnotes"><div class="footnotetext"><span class="c004">popen</span> is deprecated
now, which means we are supposed to stop using it and start using
the <span class="c004">subprocess</span> module. But for simple cases, I find
<span class="c004">subprocess</span> more complicated than necessary. So I am going
to keep using <span class="c004">popen</span> until they take it away.</div>
</dd></dl>
<p>
</td>
<td width=130 valign="top" id="col-right">
<p>
<h4>Are you using one of our books in a class?</h4> We'd like to know
about it. Please consider filling out <a href="http://spreadsheets.google.com/viewform?formkey=dC0tNUZkMjBEdXVoRGljNm9FRmlTMHc6MA" onClick="javascript: pageTracker._trackPageview('/outbound/survey');">this short survey</a>.
<p>
<br>
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491938455/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491938455&linkCode=as2&tag=greenteapre01-20&linkId=2JJH4SWCAVVYSQHO">Think DSP</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491938455" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491938455/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491938455&linkCode=as2&tag=greenteapre01-20&linkId=CTV7PDT7E5EGGJUM"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491938455&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491938455" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491929561/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491929561&linkCode=as2&tag=greenteapre01-20&linkId=ZY6MAYM33ZTNSCNZ">Think Java</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491929561" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491929561/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491929561&linkCode=as2&tag=greenteapre01-20&linkId=PT77ANWARUNNU3UK"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491929561&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491929561" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449370780/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1449370780&linkCode=as2&tag=greenteapre01-20">Think Bayes</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449370780" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449370780/ref=as_li_qf_sp_asin_il?ie=UTF8&camp=1789&creative=9325&creativeASIN=1449370780&linkCode=as2&tag=greenteapre01-20"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1449370780&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449370780" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491939362/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491939362&linkCode=as2&tag=greenteapre01-20&linkId=FJKSQ3IHEMY2F2VA">Think Python 2e</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491939362" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491939362/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491939362&linkCode=as2&tag=greenteapre01-20&linkId=ZZ454DLQ3IXDHNHX"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491939362&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491939362" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1491907339/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491907339&linkCode=as2&tag=greenteapre01-20&linkId=O7WYM6H6YBYUFNWU">Think Stats 2e</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491907339" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1491907339/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491907339&linkCode=as2&tag=greenteapre01-20&linkId=JVSYKQHYSUIEYRHL"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491907339&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491907339" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449314635/ref=as_li_tf_tl?ie=UTF8&tag=greenteapre01-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1449314635">Think Complexity</a><img class="c003" src="http://www.assoc-amazon.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449314635" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449314635/ref=as_li_tf_il?ie=UTF8&camp=1789&creative=9325&creativeASIN=1449314635&linkCode=as2&tag=greenteapre01-20"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1449314635&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://www.assoc-amazon.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449314635" width="1" height="1" border="0" alt="">
</td>
</tr>
</table>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><strong>Think Python</strong> - How to Think like a Computer Scientist (2e) <em>by Allen B. Downey</em></a>
</div>
<div>
<ul class="nav navbar-nav navbar-right">
<li><a href="http://greenteapress.com/thinkpython2/html/index.html"><span class="glyphicon glyphicon glyphicon-book" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2014.html"><span class="glyphicon glyphicon glyphicon-menu-left" aria-hidden="true"></span></a></li>
<li><a href="index.html"><span class="glyphicon glyphicon glyphicon-home" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2016.html"><span class="glyphicon glyphicon glyphicon-menu-right" aria-hidden="true"></span></a></li>
<li><a href="http://amzn.to/1VUYQUU"><span class="glyphicon glyphicon glyphicon-shopping-cart" aria-hidden="true"></span></a></li>
</ul>
<div>
</div><!-- /.container-fluid -->
</nav></body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</html>