16-读取文件内容
9.2.2 读取文件内容
既然有了一个 File
对象,就可以开始从它里面读取内容。如果你希望将整个文件的内容读取为一个字符串值,就使用 File
对象的 read()
方法。让我们继续使用保存在 helloFile
中的 hello.txt
这一 File
对象。在交互式环境中输入以下代码:
>>> helloContent = helloFile.read()
>>> helloContent
'Hello, world!'
如果你将文件的内容看成单个大字符串, read()
方法就返回保存在该文件中的这个字符串。
或者,可以使用 readlines()
方法,从该文件取得一个字符串的列表。列表中的每个字符串就是文本中的每一行。例如,在 hello.txt
所处的文件夹中,创建一个名为 sonnet29.txt
的文件,并在其中写入以下文本:
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself and curse my fate,
确保将文本分为4行。然后在交互式环境中输入以下代码:
>>> sonnetFile = open(Path.home()/'sonnet29.txt')
>>> sonnetFile.readlines()
[When, in disgrace with fortune and men's eyes,\n', ' I all alone beweep my
outcast state,\n', And trouble deaf heaven with my bootless cries,\n', And
look upon myself and curse my fate,']
请注意,除了文件的最后一行,每个字符串值都以一个换行符 \n
结束。与单个大字符串相比,字符串的列表通常更容易处理。