文章来自《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.
使用标准模块linecache处理这个任务,一般来说是最佳方法。由于lincecache缓存了文件(行?)的信息,当需要多次提取文件的某些特定行时,可以避免无用的重复操作。
如果不再需要读取文件特定行而且脚本需要继续运行,应该使用linecache的clearcache方法释放缓存占用的内存。
如果硬盘上文件有了变化,可以使
...