文件——文件实战 | 第二部分 类型与操作 —— 第 9 章: 元组,文件和其他 |《学习 python:强大的面向对象编程(第 5 版)》| python 技术论坛-金年会app官方网
让我们看一个展示文件处理基础的简单例子。下面代码开始于打开一个新的文本文件作为输出,写两行(以换行标记 \n
终止的字符串),然后关闭文件。随后,代码再次在输入模式打开同一个文件,使用 readline
一次读取一行回来。注意第三个readline
调用返回空字符串;这是python文件方法告诉你已经到文件末尾了(文件中的空行作为只含有一个换行符的字符串而非空字符串返回)。下面是完整的交互:
>>> myfile = open('myfile.txt', 'w') # open for text output: create/empty
>>> myfile.write('hello text file\n') # write a line of text: string
16
>>> myfile.write('goodbye text file\n')
18
>>> myfile.close() # flush output buffers to disk
>>> myfile = open('myfile.txt') # open for text input: 'r' is default
>>> myfile.readline() # read the lines back
'hello text file\n'
>>> myfile.readline()
'goodbye text file\n'
>>> myfile.readline() # empty string: end-of-file
''
注意在python 3.x中,文件 write
调用返回了写的字符数量;但在2.x中却不会,所以不会看到这些数字交互地回显出来。本例将文本的每一行(包含其行尾终止符 \n
)作为字符串写出;write
方法不会为我们添加行尾字符,所以我们必须添加它来恰当地终止行(否则,下一次写将简单地扩展文件中的当前行)。
如果要显示文件内容并将行尾字符解释出来,需要使用文件对象的 read
方法一次性读取整个文件到一个字符串并打印它:
>>> open('myfile.txt').read() # read all at once into string
'hello text file\ngoodbye text file\n'
>>> print(open('myfile.txt').read()) # user-friendly display
hello text file
goodbye text file
还有如果想逐行扫描文本文件,文件迭代器通常是最好的选择:
>>> for line in open('myfile.txt'): # use file iterators, not reads
... print(line, end='')
...
hello text file
goodbye text file
当以这种方式编码时,被open
创建的临时文件对象将自动地在每次循环迭代时读取和返回一行。这个形式通常是最容易编码的,在内存使用上也很好,而且可能比其它选项还要更快(当然,这取决于许多变量)。然而,因为还没有学到语句或迭代器,要获取这个代码的更完整解释,请等到第14章。
注意
windows users: as mentioned in chapter 7, open accepts unix-style
forward slashes in place of backward slashes on windows, so any of
the following forms work for directory paths—raw strings, forward
slashes, or doubled-up backslashes:
\>>> open(r'c:\python33\lib\pdb.py').readline()
'#! /usr/bin/env python3\n'
\>>> open('c:/python33/lib/pdb.py').readline()
'#! /usr/bin/env python3\n'
\>>> open('c:\\python33\\lib\\pdb.py').readline()
'#! /usr/bin/env python3\n'
the raw string form in the second command is still useful to turn off
accidental escapes when you can’t control string content, and in other
contexts.