以行的形式讀出一個(gè)文件最簡(jiǎn)單的方式是使用文件對(duì)象的readline()、readlines()和xreadlines()方法。
Python2.2+為這種頻繁的操作提供了一個(gè)簡(jiǎn)化的語(yǔ)法——讓文件對(duì)象自身在行上高效迭代(這種迭代是嚴(yán)格的向前的)。
為了讀取整個(gè)文件,可能要使用read()方法,且使用字符串的split()來(lái)將它拆分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)如果文件不大,讀取整個(gè)文件內(nèi)容也沒(méi)有關(guān)系。但如果是大文件,時(shí)間和內(nèi)存就是要重點(diǎn)關(guān)注的了。比如,復(fù)雜文檔或者活動(dòng)日志文件,通常有上M,甚至很多G的大小。就算這些文件的內(nèi)容沒(méi)有超出可用內(nèi)存的尺寸,讀取他們?nèi)匀皇窍喈?dāng)耗時(shí)的。
很明顯,如果你需要處理文件的每一行,那就必須讀取整個(gè)文件;如果可以按序列處理,xreadlines方法是一種更節(jié)約內(nèi)存的方法。但是對(duì)于那些僅僅需要一個(gè)大文件的一部分行的應(yīng)用,要獲得提高其實(shí)并不難。對(duì)于這一點(diǎn),模塊“l(fā)inecache”非常合適。
具有緩存功能的行列表
使用linecache可以直接從一個(gè)文件中讀取指定行:
>>> import linecache >>> print linecache.getline('chap1.txt',1850), PROBLEM: Working with lines from a large file記住,linecache.getline()的計(jì)數(shù)是從1開(kāi)始的。
如果有一個(gè)即具有“l(fā)inecache”的效率,又有列表的一些功能的對(duì)象就好了。這個(gè)對(duì)象不僅可以枚舉和索引,同時(shí)還支持切片。
#------------------ cachedlinelist.py --------------------# import linecache, types class CachedLineList: # Note: in Python 2.2+, it is probably worth including: # __slots__ = ('_fname') # ...and inheriting from 'object' def __init__(self, fname): self._fname = fname def __getitem__(self, x): if type(x) is types.SliceType: return [linecache.getline(self._fname, n+1) for n in range(x.start, x.stop, x.step)] else: return linecache.getline(self._fname, x+1) def __getslice__(self, beg, end): # pass to __getitem__ which does extended slices also return self[beg:end:1]使用這個(gè)新對(duì)象幾乎和使用一個(gè)由“open(fname).readlines()”創(chuàng)建的列表一樣。除了它的效率要更高之外(特別是在內(nèi)存使用方面):
>>> from cachedlinelist import CachedLineList >>> cll = CachedLineList('../chap1.txt') >>> cll[1849] ' PROBLEM: Working with lines from a large file/r/n' >>> for line in cll[1849:1851]: print line, ... PROBLEM: Working with lines from a large file ---------------------------------------------------------- >>> for line in cll[1853:1857:2]: print line, ... a matter of using the '.readline()', '.readlines()' and simplified syntax for this frequent operation by letting the
新聞熱點(diǎn)
疑難解答
圖片精選