文件——文件实战

未匹配的标注

让我们看一个展示文件处理基础的简单例子。下面代码开始于打开一个新的文本文件作为输出,写两行(以换行标记 \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.

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~