文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- 61.182.251.99 [DateTime(2004-09-20T22:17:38Z)] TableOfContents

描述

读取文件特定行

问题 Problem

读取文件的指定一行

4.5.2 Solution

解决 Solution

The standard linecache module makes this a snap:

使用标准模块linecache解决,手到擒来!

import linecache
theline = linecache.getline(thefilepath, desired_line_number)

讨论 Discussion

The standard linecache module is usually the optimal Python solution for this task, particularly if you have to do this repeatedly for several of a file's lines, as it caches the information it needs to avoid uselessly repeating work. Just remember to use the module's clearcache function to free up the memory used for the cache, if you won't be getting any more lines from the cache for a while but your program keeps running. You can also use checkcache if the file may have changed on disk and you require the updated version.

...

参考 See Also