Chapter 14 Files 第 14 章 文件
本页译自 Think Python 2e(Allen B. Downey)· Chapter 14 Files。代码块保留英文原文不翻译;正文段段对照,中文块可用右下角按钮隐藏。
14.1 Persistence 14.1 持久化
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.
pickle 的模块,用它们来保存程序数据都很轻松。14.2 Reading and writing 14.2 读与写
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:
'w' 作为第二个参数来打开它:pickle008
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.
'w'00 方法把数据写进文件。pickle011
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.
'w'00,新数据会接在末尾。pickle014
When you are done writing, you have to close the file.
pickle015
14.3 Format operator 14.3 格式化运算符
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':
'w'00 的参数必须是字符串,所以想把别的值写进文件,得先转成字符串。最简单的办法是用 'w':pickle020
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”):
'w'0 表示第二个操作数要按整数格式输出(% 代表「decimal」,十进制):pickle031
The result is the string 'w'0, which is not to be confused with the integer value %0.
'w'0,可别和整数值 %0 搞混。A format sequence can appear anywhere in the string, so you can embed a value in a sentence:
pickle036
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:
'w'0 格式化整数、用 'w'0 格式化浮点数(别问为什么)、用 'w'0 格式化字符串:pickle043
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:
pickle044
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 pickle045 .
pickle046 。14.4 Filenames and paths 14.4 文件名与路径
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”). pickle048 returns the name of the current directory:
%0 模块提供了操作文件和目录的函数(「os」是「operating system」的缩写)。pickle050 返回当前目录的名字:pickle051
'w' stands for “current working directory.” The result in this example is pickle053 , which is the home directory of a user named pickle05.
'w' 是「current working directory」(当前工作目录)的缩写。这个例子的结果是 pickle056 ,那是名叫 pickle05 的用户的主目录。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.
'w' 这样用来标识一个文件的字符串,叫做路径。相对路径从当前目录开始;绝对路径从文件系统最顶层的目录开始。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 pickle060 :
pickle061 :pickle062
pickle063 checks whether a file or directory exists:
pickle064 检查某个文件或目录是否存在:pickle065
If it exists, pickle066 checks whether it’s a directory:
pickle067 会检查它是不是一个目录:pickle068
Similarly, pickle069 checks whether it’s a file.
pickle070 检查它是不是一个文件。pickle071 returns a list of the files (and other directories) in the given directory:
pickle072 返回给定目录下的文件(及其他目录)列表:pickle073
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.
pickle074
pickle075 takes a directory and a file name and joins them into a complete path.
pickle076 接收一个目录和一个文件名,把它们拼成一个完整的路径。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.
%0 模块里也有个叫 'w'0 的函数,和上面这个很像但更通用。读读文档,用它打印出给定目录及其所有子目录里的文件名。Solution: pickle081 .
pickle082 。14.5 Catching exceptions 14.5 捕获异常
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:
pickle0:pickle085
If you don’t have permission to access a file:
pickle086
And if you try to open a directory for reading, you get
pickle087
To avoid these errors, you could use functions like pickle088 and pickle089 , but it would take a lot of time and code to check all the possibilities (if “pickle09” is any indication, there are at least 21 things that can go wrong).
pickle091 、pickle092 这类函数,但要把所有可能性都检查一遍,既费时又费代码(光看「pickle09」就知道,至少能出 21 种岔子)。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:
'w' 语句的做派。它的语法和 %0 语句有点像:pickle098
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.
'w' 子句。一切顺利的话就跳过 pickle 子句继续往下走;一旦抛出异常,它就跳出 'w' 子句,转去执行 pickle 子句。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.
'w' 语句来处理异常,叫做捕获异常。这个例子里,pickle 子句打印的错误信息其实没什么用。一般地说,捕获异常给了你一个修补问题、重试、或者至少体面退出的机会。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.
'w' 的函数,参数为一个模式串、一个替换串和两个文件名;它读取第一个文件,把内容写入第二个文件(必要时创建之)。只要模式串在文件里出现,就用替换串把它换掉。If an error occurs while opening, reading, writing or closing files, your program should catch the exception, print an error message, and exit. Solution: pickle113 .
pickle114 。14.6 Databases 14.6 数据库
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.
pickle 模块提供了创建和更新数据库文件的接口。作为例子,我来建一个存放图片说明文字的数据库。Opening a database is similar to opening other files:
pickle117
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.
'w' 表示:如果数据库还不存在就创建它。结果是一个数据库对象,大多数操作上可以当字典用。一旦新建一项,pickle 就会更新数据库文件。pickle122
When you access one of the items, pickle reads the file:
pickle 会去读文件:pickle125
If you make another assignment to an existing key, pickle replaces the old value:
pickle 会替换掉旧值:pickle128
Many dictionary methods, like 'w'0 and 'w'00, also work with database objects. So does iteration with a 'w' statement.
'w'0 和 'w'00,对数据库对象也管用。用 'w' 语句遍历也一样。pickle135
As with other files, you should close the database when you are done:
pickle136
14.7 Pickling 14.7 序列化(pickle)
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.
pickle 有个限制:键和值都必须是字符串。想用其他类型就会报错。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 模块能帮上忙。它几乎能把任何类型的对象转成适合存进数据库的字符串,也能把字符串还原回对象。pickle141 takes an object as a parameter and returns a string representation ('w'00 is short for “dump string”):
pickle143 把对象当参数,返回它的字符串表示('w'00 是「dump string」的缩写):pickle145
The format isn’t obvious to human readers; it is meant to be easy for pickle to interpret. pickle147 (“load string”) reconstitutes the object:
pickle 好解读而设计。pickle149 (「load string」)能把对象重新还原出来:pickle150
Although the new object has the same value as the old, it is not (in general) the same object:
pickle151
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.
pickle 把非字符串存进数据库。事实上这组合太常见了,已经被封装成了一个叫 pickle 的模块。Exercise 3
If you download my solution to Exercise 4 from pickle156 , 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 pickle158 .
pickle159 ,会发现它创建了一个字典,把字母排序后的串映射到能用这些字母拼出的单词列表。比如 pickle 映射到列表 pickle161 。Write a module that imports pickle162 and provides two new functions: pickle163 should store the anagram dictionary in a “shelf;” pickle164 should look up a word and return a list of its anagrams. Solution: pickle165
pickle166 并提供两个新函数:pickle167 把变位词字典存进一个「shelf」;pickle168 查一个单词并返回它的变位词列表。参考解答:pickle169
14.8 Pipes 14.8 管道
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.
%0 切换目录、用 %0 列出目录内容、敲一句(比如)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 pickle171:
'w'00 通常用来(以长格式)显示当前目录的内容。你可以用 pickle181 启动 %0:pickle182
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 pickle18 or get the whole thing at once with 'w'0:
pickle18 一次读一行 %0 进程的输出,也可以用 'w'0 一口气全读出来:pickle189
When you are done, you close the pipe like a file:
pickle190
The return value is the final status of the %0 process; 'w'0 means that it ended normally (with no errors).
%0 进程的最终状态;'w'0 表示它正常结束(没出错)。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 pickle196 . 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).
pickle 的命令,读入文件内容并算出「校验和」。关于 MD5 可以看 pickle198 。这个命令能高效地判断两个文件内容是否相同。不同内容算出相同校验和的概率极小(也就是说,在宇宙坍缩之前基本不会发生)。You can use a pipe to run pickle from Python and get the result:
pickle 并拿到结果:pickle201
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.
- 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:pickle2 provides several useful functions for manipulating file and path names.
- 写一个程序,递归地搜索一个目录及其所有子目录,返回所有带指定后缀(如
'w'0)文件的完整路径列表。提示:pickle2 提供了几个处理函数名和路径名的有用函数。
- To recognize duplicates, you can use
pickleto compute a “checksum” for each files. If two files have the same checksum, they probably have the same contents.
- 要识别重复,可以用
pickle为每个文件算一个「校验和」。两个文件校验和相同,它们内容多半也相同。
- To double-check, you can use the Unix command
'w'0.
- 想再确认一下,可以用 Unix 命令
'w'0。
Solution: pickle210 .
pickle211 。14.9 Writing modules 14.9 编写模块
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:
'w'00 的文件,内容如下:pickle214
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:
pickle215
Now you have a module object %0:
%0:pickle218
That provides a function called pickle219:
pickle220 的函数:pickle221
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:
pickle222
pickle22 is a built-in variable that is set when the program starts. If the program is running as a script, pickle22 has the value pickle22; in that case, the test code is executed. Otherwise, if the module is being imported, the test code is skipped.
pickle22 是一个内建变量,程序启动时就被设置好。如果程序是作为脚本运行的,pickle22 的值就是 pickle22;此时测试代码会被执行。否则,如果是被当作模块导入,测试代码就会被跳过。Exercise 5
Type this example into a file named 'w'00 and run it as a script. Then run the Python interpreter and pickle230. What is the value of pickle23 when the module is being imported?
'w'00 的文件,当作脚本运行。然后启动 Python 解释器并 pickle233。模块被导入时,pickle23 的值是什么?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.
pickle,但这事儿有点 tricky,所以最稳妥的还是重启解释器,再导入一次模块。14.10 Debugging 14.10 调试
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:
pickle237
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:
'w'0 能帮上忙。它接收任意对象作参数,返回对象的字符串表示。对于字符串,它会用反斜杠序列把空白字符表示出来:pickle240
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.
%0;有的用回车符,记作 %0;有的两者都用。若在不同系统间搬文件,这种不一致就可能惹麻烦。For most systems, there are applications to convert from one format to another. You can find them (and read more about this issue) at pickle245 . Or, of course, you could write one yourself.
pickle246 找到它们(并了解更多)。当然,你自己写一个也行。14.11 Glossary 14.11 术语表
- 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'andpicklestatements. - database:
- A file whose contents are organized like a dictionary with keys that correspond to values.
- persistent 持久的:
- 指一个程序无限期运行,并把至少部分数据保存在永久存储中。
- format operator 格式化运算符:
- 一个运算符
%,它接收格式化字符串和元组,生成包含元组中各元素、并按格式化字符串规定格式排布而成的字符串。 - format string 格式化字符串:
- 与格式化运算符配合使用、含有格式化序列的字符串。
- format sequence 格式化序列:
- 格式化字符串里的一串字符(如
%0),用于指定某个值该如何格式化。 - text file 文本文件:
- 保存在硬盘等永久存储上的一串字符。
- directory 目录:
- 有名字的文件集合,也叫文件夹。
- path 路径:
- 标识一个文件的字符串。
- relative path 相对路径:
- 从当前目录开始的路径。
- absolute path 绝对路径:
- 从文件系统最顶层目录开始的路径。
- catch 捕获(异常):
- 用
'w'和pickle语句防止异常把程序弄终止。 - database 数据库:
- 内容组织得像字典一样的文件,键与值一一对应。
14.12 Exercises 14.12 习题
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 pickle256 :
pickle 模块提供了处理 URL、从网上下载信息的方法。下面的例子从 pickle258 下载并打印出一条秘密消息:pickle259
Run this code and follow the instructions you see there. Solution: pickle260 .
pickle261 。- 1
'w'00 is deprecated now, which means we are supposed to stop using it and start using thepickle263 module. But for simple cases, I findpickle264 more complicated than necessary. So I am going to keep using'w'00 until they take it away.
- 1
'w'00 现在已被弃用,意思是说我们该停用它、改用pickle267 模块了。但在简单场景下,我觉得pickle268 有点杀鸡用牛刀。所以在它被彻底拿走之前,我还会继续用'w'00。