7.2.1 文件对象(file object)的方法 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. 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 或者指定为负数,就会读取并返回整个文件。当文件大小为当前机器内存两倍时,就会产生问题。正常情况下,会尽可能按比较大的 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() 从文件中读取单独一行,字符串结尾会自动加上一个换行符,只有当文件最后一行没有以换行符结尾时,这一操作才会被忽略。这样返回值就不会有什么混淆不清,如果 如果 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']

f.write(string) writes the contents of string to the file, returning None.

f.write(string)string 的内容写入文件,返回 None

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

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 可以忽略,其默认值为零,此时从文件头开始。

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

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

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()truncate() 在库参考手册中有文件对象的完整指南。