以行的形式讀出一個(gè)文件最簡單的方式是使用文件對(duì)象的readline()、readlines()和xreadlines()方法。
Python2.2+為這種頻繁的操作提供了一個(gè)簡化的語法——讓文件對(duì)象自身在行上高效迭代(這種迭代是嚴(yán)格的向前的)。
為了讀取整個(gè)文件,可能要使用read()方法,且使用字符串的split()來將它拆分WEIGHT行或其他塊。
下面是一些例子:
>>> for line in open('chap1.txt'): # Python 2.2+ ... # process each line in some manner ... pass ... >>> linelist = open('chap1.txt').readlines() >>> print linelist[1849], EXERCISE: Working with lines from a large file >>> txt = open('chap1.txt').read() >>> from os import linesep >>> linelist2 = txt.split(linesep)