读取、写入和 Python
编写程序的最后一个基本步骤就是从文件读取数据和把数据写入文件。阅读完这篇文章之后,可以在自己的 to-do 列表中加上检验这个技能学习效果的任务。
简单输出
贯穿整个系列,一直用 print 语句写入(输出)数据,它默认把表达式作为 string 写到屏幕上(或控制台窗口上)。清单 1 演示了这一点。清单 1 重复了第一个 Python 程序 “Hello, World!”,但是做了一些小的调整。
清单 1. 简单输出
>>> print "Hello World!"
Hello World!
>>> print "The total value is = $", 40.0*45.50
The total value is = $ 1820.0
>>> print "The total value = $%6.2f" % (40.0*45.50)
The total value = $1820.00
>>> myfile = file("testit.txt", 'w')
>>> print >> myfile, "Hello World!"
>>> print >> myfile, "The total value = $%6.2f" % (40.0*45.50)
>>> myfile.close()
</div>
正如这个示例演示的,用 print 语句写入数据很容易。首先,示例输出一个简单的 string。然后创建并输出复合的 string,这个字符串是用 string 格式化技术创建的。
但是,在这之后,事情发生了变化,与代码以前的版本不同。接下来的一行创建 file 对象,传递进名称 "testit.txt" 和 'w' 字符(写入文件)。然后使用修改过的 print 语句 —— 两个大于号后边跟着容纳 file 对象的变量 —— 写入相同的 string。但是这一次,数据不是在屏幕上显示。很自然的问题是:数据去哪儿了?而且,这个 file 对象是什么?
第一个问题很容易回答。请查找 testit.txt 文件,并像下面那样显示它的内容。
% more testit.txt Hello World! The total value = $1820.00</div>
可以看到,数据被准确地写入文件,就像以前写到屏幕上一样。
现在,请注意清单 1 中的最后一行,它调用 file 对象的 close 方法。在 Python 程序中这很重要,因为在默认情况下,文件输入和输出是缓冲的;在调用 print 语句时,数据实际未被写入;相反,数据是成批写入的。让 Python 把数据写入文件的最简单方式就是显式地调用 close 方法。
文件对象
file 是与计算机上的文件进行交互的基本机制。可以用 file 对象读取数据、写入数据或把数据添加到文件,以及处理二进制或文本数据。
学习 file 对象的最简单方法就是阅读帮助,如清单 2 所示。
清单 2. 得到 file 对象的帮助
>>> help(file) Help on class file in module __builtin__: class file(object) | file(name[, mode[, buffering]]) -> file object | | Open a file. The mode can be 'r', 'w' or 'a' for reading (default), | writing or appending. The file will be created if it doesn't exist | when opened for writing or appending; it will be truncated when | opened for writing. Add a 'b' to the mode for binary files. | Add a '+' to the mode to allow simultaneous reading and writing. | If the buffering argument is given, 0 means unbuffered, 1 means line | buffered, and larger numbers specify the buffer size. | Add a 'U' to mode to open the file for input with universal newline | support. Any line ending in the input file will be seen as a '\n' | in Python. Also, a file so opened gains the attribute 'newlines'; | the value for this attribute is one of None (no newline read yet), | '\r', '\n', '\r\n' or a tuple containing all the newline types seen. | | 'U' cannot be combined with 'w' or '+' mode. | | Note: open() is an alias for file(). | | Methods defined here: ...</div>
正如帮助工具指出的,使用 file 对象很简单。用 file 构造函数或 open 方法创建 file 对象,open 是 file 构造函数的别名。第二个参数是可选的,它指定文件的使用方式:
- 'r' (默认值)表示从文件读取数据。
- 'w' 表示要向文件写入数据,并截断以前的内容。
- 'a' 表示要向文件写入数据,但是添加到当前内容尾部。
- 'r+' 表示对文件进行读写操作(删除以前的所有数据)。
- 'r+a' 表示对文件进行读写操作(添加到当前内容尾部)。
- 'b' 表示要读写二进制数据。
这篇文章的第一个代码清单向文件写入数据。现在,清单 3 显示如何把这个数据读入 Python 程序,并解析文件的内容。
清单 3. 从文件读取数据
>>> myfile = open("testit.txt")
>>> myfile.read()
'Hello World!\nThe total value = $1820.00\n'
>>> str = myfile.read()
>>> print str
>>> myfile.seek(0)
>>> str = myfile.read()
>>> print str
Hello World!
The total value = $1820.00
>>> str.split()
['Hello', 'World!', 'The', 'total', 'value', '=', '$1820.00']
>>> str.split('\n')
['Hello World!', 'The total value = $1820.00', '']
>>> for line in str.split('\n'):
... print line
...
Hello World!
The total value = $1820.00
>>> myfile.close()
</div>
要读取数据,首先要创建合适的 file 对象 —— 在这个示例中,文件对象打开 testit.txt 文件,并用 read 方法读取内容。这个方法把整个文件读入一个 string,然后在程序中把这个字符串输出到控制台。在对 read 方法的第二个调用中,试图把值分配给 str 变量,结果返回一个空的 string。这是因为第一个 read 操作读入了整个文件。当试图再次读取内容时,已经到了文件末尾,所以什么也读不到。
这个问题的解决方案也很简单:让 file 对象返回文件的开头。回到开头要通过 seek 方法进行,它接受一个参数,表示要从文件中的什么位置开始读取或写入(例如,0 代表文件开头)。seek 方法支持更复杂的操作,但是可能会有危险。对于目前来说,我们还坚持采用简单方式。
现在回到了文件的开始之处,可以把文件内容读入 string 变量并对 string 做适当地解析。请注意,在文件中,行之间用新行(或行结束)字符区分。如果试着在 string 上调用 split 方法,它会在空白字符(例如空格)处进行拆分。为了让方法根据新行字符拆分各行,必须显式地指定新行字符。然后可以拆分 string 并在 for 循环中对文件的行进行迭代。
看起来仅仅从文件中读取和处理一行内容都有许多工作要做。Python 要让简单的事情变容易,所以您可能想知道这个任务有没有快捷方式可用。如清单 4 所示,答案是 yes。
清单 4. 读取和解析行
>>> myfile = open("testit.txt")
>>> for line in myfile.readlines():
... print line
...
Hello World!
The total value = $1820.00
>>> myfile.close()
>>> for line in open("testit.txt").readlines():
... print line
...
Hello World!
The total value = $1820.00
>>> for line in open("testit.txt"):
... print line
...
Hello World!
The total value = $1820.00
</div>
清单 4 演示了读取和解析文本文件行的三种技术。首先,打开文件并把它分配给变量。然后调用 readlines 方法,把整个文件读入内存并把内容拆分成 string 列表。for 循环在 string 列表上进行迭代,一次输出一行。
第二个 for 循环通过使用 file 对象的隐式变量(也就是说,变量不是显式创建的),对这个过程稍做了点儿简化。打开文件和读取文件内容一次完成,生成的效果与第一个显式示例相同。最后一个示例进一步做了简化,并演示了直接在 file 对象上进行迭代的能力(请注意,这是 Python 的一个新特性,所以在您的计算机上可能无法工作)。在这个示例中,创建隐式 file 对象,然后 Python 做余下的工作,允许对文件中的全部行进行迭代。
但是,有些时候,在从文件读取数据时,可能想要更好的控制级别。在这种情况下,应当使用 readline 方法,如清单 5 所示。
清单 5. 读取数据
>>> myfile = open("testit.txt")
>>> myfile.readline()
'Hello World!\n'
>>> myfile.readline()
'The total value = $1820.00\n'
>>> myfile.readline()
''
>>> myfile.seek(0)
>>> myfile.readline()
'Hello World!\n'
>>> myfile.tell()
13L
>>> myfile.readline()
'The total value = $1820.00\n'
>>> myfile.tell()
40L
>>> myfile.readline()
''
>>> myfile.tell()
40L
>>> myfile.seek(0)
>>> myfile.read(17)
'Hello World!\nThe '
>>> myfile.seek(0)
>>> myfile.readlines(23)
['Hello World!\n', 'The tot

