7. Input and Output 输入输出

There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities.

一个程序可以有几种输出方式:以人类可读的方式打印数据,或者写入一个文件供以后使用。 本章将讨论几种可能性。

7.1. Fancier Output Formatting 格式化输出

So far we’ve encountered two ways of writing values: expression statements and the print() function. (A third way is using the write() method of file objects; the standard output file can be referenced as sys.stdout. See the Library Reference for more information on this.)

到目前为止,我们已经解除了两种输出值的方法: 表达式语句print() 函数。 (第三种方式是使用文件对象的 write() 方法,标准文件输出可以参考 sys.stdout 库手册。)

Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are two ways to format your output; the first way is to do all the string handling yourself; using string slicing and concatenation operations you can create any layout you can imagine. The standard module string contains some useful operations for padding strings to a given column width; these will be discussed shortly. The second way is to use the str.format() method.

通常,你想要对输出做更多的格式控制,而不是简单的打印使用空格分隔的值。 有两种方法可以格式化你的输出: 第一种方法是由你自己处理整个字符串,通过使用字符串切割和连接操作可以创建任何你想要的输出形式。 标准模块 string 包含一些将字符串填充到指定列宽度的有用操作,随后就会讨论这些。 第二种方法是使用 str.format() 方法。

The string module contains a class Template which offers yet another way to substitute values into strings.

string 模块包含一个模版类,还支持另一种将值替换为字符串的方法。

One question remains, of course: how do you convert values to strings? Luckily, Python has ways to convert any value to a string: pass it to the repr() or str() functions.

当然,还有一个问题:你如何将值转换为字符串? 幸运的是,Python有几种方法可以将任何值转换为一个字符串:将它传递给 repr() 函数或 str() 函数。

The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is not equivalent syntax). For objects which don’t have a particular representation for human consumption, str() will return the same value as repr(). Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function. Strings and floating point numbers, in particular, have two distinct representations.

str() 函数返回值的人类可读的表示形式,而 repr() 函数则生成可以由解释器读取的表现形式(如果没有相等的语法则产生一个 SyntaxError 错误)。 对于那些没有一个特别的可供人类使用的表示形式的对象, str()repr() 将返回同样的值。 大多数值在使用两个函数时都会有相同的表现形式,像数字或者类似列表和字典的结构。 特别的,字符串和浮点数具有两种独特的表现形式。

Some examples:

下面是一些示例:

>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(0.1)
'0.1'
>>> repr(0.1)
'0.10000000000000001'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"

Here are two ways to write a table of squares and cubes:

这里是两种输出平方和立方表格的方法:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # Note use of 'end' on previous line
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

>>> for x in range(1, 11):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

(Note that in the first example, one space between each column was added by the way print() works: it always adds spaces between its arguments.)

(注意:在第一个例子中使用 print() 函数时在每列之间添加了一个空格——它总是会在参数之间添加空格。)

This example demonstrates the rjust() method of string objects, which right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods ljust() and center(). These methods do not write anything, they just return a new string. If the input string is too long, they don’t truncate it, but return it unchanged; this will mess up your column lay-out but that’s usually better than the alternative, which would be lying about a value. (If you really want truncation you can always add a slice operation, as in x.ljust(n)[:n].)

这个示例演示了字符串对象的 rjust() 方法,它通过在字符串左侧填充指定宽度的空格以使其右对齐。 还有两个类似的方法: ljust()center() 。 这些方法不输出任何东西,它们仅仅返回一个新字符串。 如果输入的字符串过长,它们不会截短它,而是原样返回。 这也许会使你的列布局混乱,但总比截短它更好,那样会输出错误的值。 (如果你确实想要截短,你总是可以使用切片操作,如 x.ljust(n)[:n] 。)

There is another method, zfill(), which pads a numeric string on the left with zeros. It understands about plus and minus signs.

还有另一个方法: zfill() ,使用零在数字字符串左侧填充(到指定宽度)。 它可以理解正负号。

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

Basic usage of the str.format() method looks like this:

str.format() 方法基本的用法类似这样:

>>> print('We are the {0} who say "{1}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"

The brackets and characters within them (called format fields) are replaced with the objects passed into the format method. The number in the brackets refers to the position of the object passed into the format method.

括号及其包含的字符(称作格式化域)会被传递给格式化方法的对象替换。 括号中的数字指代传递给格式化方法对象的位置。

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

If keyword arguments are used in the format method, their values are referred to by using the name of the argument.

如果在格式化方法中使用了关键字参数,它们的值可以通过参数名指代。

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

Positional and keyword arguments can be arbitrarily combined:

位置参数和关键字参数可以随意混合使用:

>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
                                                       other='Georg'))
The story of Bill, Manfred, and Georg.

An optional ':' and format specifier can follow the field name. This also greater control over how the value is formatted. The following example truncates the Pi to three places after the decimal.

字段名称后面可以跟一个可选的 ':' 符号和格式化分类符。 这也是如何更好的控制格式化值的方法。 下面的示例将PI小数点后截短为三位。

>>> import math
>>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))
The value of PI is approximately 3.142.

Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making tables pretty.

通过在 ':' 后面传递一个整数可以限定那个字段的最小字符宽度。 这对美化表格非常有用。

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print('{0:10} ==> {1:10d}'.format(name, phone))
...
Jack       ==>       4098
Dcab       ==>       7678
Sjoerd     ==>       4127

If you have a really long format string that you don’t want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by simply passing the dict and using square brackets '[]' to access the keys.

如果你有一个不想分割的确实很长的字符串,使用名称替代位置来引用被格式化的变量将会更好。 这可以简单的通过传递一个字典并且使用方括号 '[]' 访问所有的键。

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
          'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This could also be done by passing the table as keyword arguments with the ‘**’ notation.

这同样可以使用“**”表示法将table变量当作关键字参数传递做到(即对字典进行拆分)。

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This is particularly useful in combination with the new built-in vars() function, which returns a dictionary containing all local variables.

这在与新的内置函数 vars() 结合时尤为有用,它返回一个包含所有本地变量的字典。

For a complete overview of string formatting with str.format(), see Format String Syntax.

字符串格式化方法 str.format() 的完整介绍请参考 Format String Syntax

7.1.1. Old string formatting 旧式字符窜格式化

The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation. For example:

% 操作符同样可以用来格式化字符串。 它像 :cfunc:`sprintf- 格式化字符串风格一样解释左参数并作用于右参数,并且从该格式化操作中返回字符串结果。 例如:

>>> import math
>>> print('The value of PI is approximately %5.3f.' % math.pi)
The value of PI is approximately 3.142.

Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually removed from the language str.format() should generally be used.

因为 str.format() 方法十分新颖,大多数Python代码仍然使用 % 操作。 然后,因为这种旧式风格的格式化最终将从Python中废除,一般应该使用 str.format() 方法。

More information can be found in the Old String Formatting Operations section.

更多信息可以参考 Old String Formatting Operations 章节。

7.2. Reading and Writing Files 文件读写

open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

open() 函数返回一个文件对象,并且它通常带有两个参数: open(filename, mode)

>>> f = open('/tmp/workfile', 'w')

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

第一个参数是一个包含文件名的字符串。 第二个参数是另一个包含几个字符的字符串,描述了文件使用的方式。 当文件为只读时 mode 取值为 'r' ,只写时为 'w' (如果存在同名的文件则会被覆盖); 'a' 表示以追加方式打开文件,所有的数据都会被自动的添加到文件末尾。 'r+' 表示以读写方式打开文件。 参数 mode 是可选的,默认值为 'r' (即只读)。

Normally, files are opened in text mode, that means, you read and write strings from and to the file, which are encoded in a specific encoding (the default being UTF-8). 'b' appended to the mode opens the file in binary mode: now the data is read and written in the form of bytes objects. This mode should be used for all files that don’t contain text.

通常,文件是以 text mode (文本模式)方式打开,即你从文件中读写字符串都是以一种特殊编码(默认为UTF-8)进行编码的。 可以通过在常用模式后添加 'b' 选项从而以 binary mode (二进制模式)打开文件,现在数据就是以字节码对象形式来读写了。 这种模式可以用在所有非文本文件中。

In text mode, the default is to convert platform-specific line endings (\n on Unix, \r\n on Windows) to just \n on reading and \n back to platform-specific line endings on writing. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.

在文本模式中,在读取文件时默认会将特定平台的行结束符(Unix为 \n ,Windows为 \r\n )转换为 \n ,并在写入文件时转换回去。 这种对文件数据的后台修改是对文本文件是无害的,但它会破坏像 JPEGEXE 文件中的二进制数据。 在读写这类文件时,你应该十分小心的使用二进制模式。

7.2.1. Methods of File Objects 文件对象的方法

The rest of the examples in this section will assume that a file object called f has already been created.

本节中剩下的示例都假设已经创建了一个名为 f 的文件对象。

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string or bytes object. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ('').

想要读取一个文件的内容,可以调用 f.read(size) 方法,该方法读取若干数量的数据并以字符串或字节码对象形式返回。 size 是一个可选的数值参数。 如果没有指定 size 或者它为负数,就会读取并返回文件的全部内容。 如果文件大小是你机器内容的两倍大时,这会让你面临问题。 不过,你应该以尽可能大字节读取文件内容。 如果已经达到文件尾, f.read() 将返回一个空字符串( '' )。

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

f.readline() 方法从文件中读取单独一行内容,字符串结尾会带有一个换行符( \n ),并且仅当文件最后一行结尾没有换行符时才会被省略。 这样就让返回值清晰明了了,如果 f.readline() 返回一个空字符串就表示到达文件尾了。 当用 '\n' 表示一个空行时,将返回一个只含有一个换行符的字符串。

>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''

f.readlines() returns a list containing all the lines of data in the file. If given an optional parameter sizehint, it reads that many bytes from the file and enough more to complete a line, and returns the lines from that. This is often used to allow efficient reading of a large file by lines, but without having to load the entire file in memory. Only complete lines will be returned.

f.readlines() 方法返回一个包含文件所有数据行的列表。 如果指定了可选的 sizehint 参数,它就会从文件中读取至少包含指定字节数的完整行并返回之。 这通常被用来从一个大文件中以行的形式高效的读取内容,而不是将整个文件加载到内存。 此方法只返回完整的行。

>>> f.readlines()
['This is the first line of the file.\n', 'Second line of the file\n']

An alternative approach to reading lines is to loop over the file object. This is memory efficient, fast, and leads to simpler code:

一种替代的方法是通过遍历文件对象来读取文件行。 这是一种内存高效、快速,并且代码简介的方式:

>>> for line in f:
...     print(line, end='')
...
This is the first line of the file.
Second line of the file

The alternative approach is simpler but does not provide as fine-grained control. Since the two approaches manage line buffering differently, they should not be mixed.

虽然这种替代方法更简单,但并不具备细节控制能力。 因为这两种方法处理行缓存的方式不同,千万不能搞混。

f.write(string) writes the contents of string to the file, returning the number of characters written.

f.write(string) 方法将 string 的内容写入文件,并返回写入字符的长度。

>>> f.write('This is a test\n')
15

To write something other than a string, it needs to be converted to a string first.

想要写入其他非字符串内容,首先要将它转换为字符串。

>>> value = ('the answer', 42)
>>> s = str(value)
>>> f.write(s)
18

f.tell() returns an integer giving the file object’s current position in the file, measured in bytes from the beginning of the file. To change the file object’s position, use f.seek(offset, from_what). The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point.

f.tell() 方法返回一个指代文件对象当前位置的整数,表示从文件开头到当前位置的字节数。 想要改变文件对象位置,你可以使用 f.seek(offset, from_what) 方法。 新的位置是通过将 offset 值与参考点相加计算得来的,参考点是由 from_what 参数确定的。 如果 from_what 值为0则代表从文件头开始计算,值为1时代表从当前文件位置开始计算,值为2时代表从文件尾开始计算。 from_what 参数可以省略并且其默认值为0,即使用文件头作为参考点。

>>> f = open('/tmp/workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)     # Go to the 6th byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
13
>>> f.read(1)
b'd'

In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2)).

在文本文件中(那些没有使用 b 模式选项打开的文件),只允许从文件头开始计算相对位置(使用 seek(0, 2) 从文件尾计算时就会引发异常)。

When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

当你使用完一个文件时,调用 f.close() 方法就可以关闭它并释放其占用的所有系统资源。 在调用 f.close() 方法后,试图再次使用文件对象将会自动失败。

>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks.

当处理文件对象时,使用 with 关键字是个好习惯。 这是由好处的:在文件一系列操作后它会被适当的关闭,甚至从某种意义上说异常也会变的可爱。

>>> with open('/tmp/workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

File objects have some additional methods, such as isatty() and truncate() which are less frequently used; consult the Library Reference for a complete guide to file objects.

文件对象还有一些其他的方法,像 isatty`和:meth:`truncate() ,但它们都不常用。 关于文件对象完整示例请查阅库参考手册。

7.2.2. The pickle Module :mod:`pickle`模块

Strings can easily be written to and read from a file. Numbers take a bit more effort, since the read() method only returns strings, which will have to be passed to a function like int(), which takes a string like '123' and returns its numeric value 123. However, when you want to save more complex data types like lists, dictionaries, or class instances, things get a lot more complicated.

从文件中可以很容易的读写字符串。 数字可能需要额外的处理,因为 read() 方法只能返回字符串。 必须将它传递给像 in() 一样的函数,此类函数接收一个字符串并返回它数值,像 '123' 就返回123。 然而,当你想保存更复杂的数据类型时事情会变的尤为复杂,像列表、字典或者对象实例等。

Rather than have users be constantly writing and debugging code to save complicated data types, Python provides a standard module called pickle. This is an amazing module that can take almost any Python object (even some forms of Python code!), and convert it to a string representation; this process is called pickling. Reconstructing the object from the string representation is called unpickling. Between pickling and unpickling, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine.

好在用户无需经常编写和调试保存复杂数据类型的代码,Python提供了一个名为 pickle 的标准模块。 这是一个惊艳的模块,它几乎可以将任何Python对象(甚至是一些Python代码!)转换为字符串表示形式,这个过程称为 pickling (封装)。 从这个字符串表示形式中重建Python对象被称为 unpickling (拆封)。 在 picklingunpickling 之间,字符串表示的对象可以存储在文件或数据中,或者可以通过网络连接发送给远程的机器。

If you have an object x, and a file object f that’s been opened for writing, the simplest way to pickle the object takes only one line of code:

如果你有一个对象 x 对象和一个已经打开并等待写入的文件对象 f ,封装(pickling)对象的最简单方法之需要一行代码:

pickle.dump(x, f)

To unpickle the object again, if f is a file object which has been opened for reading:

想要拆封(unpickling)这个对象,如果存在一个已经打开并等待读取的文件对象 f ,即可:

x = pickle.load(f)

(There are other variants of this, used when pickling many objects or when you don’t want to write the pickled data to a file; consult the complete documentation for pickle in the Python Library Reference.)

(当封装许多对象时,或者你不想把封装数据写入一个文件,这可以有其他的变化。请查阅Python库文档获取关于 pickle 完整的文档。)

pickle is the standard way to make Python objects which can be stored and reused by other programs or by a future invocation of the same program; the technical term for this is a persistent object. Because pickle is so widely used, many authors who write Python extensions take care to ensure that new data types such as matrices can be properly pickled and unpickled.

pickle 模块将Python对象转换为可以存储并提供给其他程序或其自身以后调用的标准方法,术语称为 persistent 对象(持久化对象)。 pickle 模块被如此广泛的使用,许多Python扩展开发者都非常注意像矩阵这样的新数据类型是否可以被适当的封装和拆封。