Differences between revisions 1 and 4 (spanning 3 versions)
Revision 1 as of 2004-09-20 22:17:38
Size: 1154
Editor: 61
Comment:
Revision 4 as of 2004-09-20 22:41:49
Size: 1756
Editor: 61
Comment:
Deletions are marked like this. Additions are marked like this.
Line 26: Line 26:
使用标准模块'''linecache'''解决手到擒来! 使用标准模块'''linecache'''处理很简单:
Line 33: Line 33:
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'''方法释放缓存占用的内存。

使用'''checkcache'''方法可以检查磁盘文件是否已经变化,如果变化可以更新缓存信息。

'''linecache'''读取并缓存作为参数传入的文件的全部信息。如果处理一个很大的文件,而且只需要读取某一个特定行,使用'''linecache'''可能会进行不是严格必须的操作。如果这个例程恰好是程序性能瓶颈,可以编写函数,封装循环代码,以获得性能提升。 Python 2.2中代码如下:
{{{
def getline(thefilepath, desired_line_number):
    if desired_line_number < 1: return ''
    current_line_number = 0
    for line in open(thefilepath):
        current_line_number += 1
        if current_line_number == desired_line_number: return line
    return ''
}}}
Line 36: Line 52:
...

文章来自《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

使用标准模块linecache处理这个任务,一般来说是最佳方法。由于lincecache缓存了文件的信息,当需要多次提取文件的某些特定行时,可以避免无用的重复操作。

如果不再需要读取文件特定行而且脚本需要继续运行,应该使用linecacheclearcache方法释放缓存占用的内存。

使用checkcache方法可以检查磁盘文件是否已经变化,如果变化可以更新缓存信息。

linecache读取并缓存作为参数传入的文件的全部信息。如果处理一个很大的文件,而且只需要读取某一个特定行,使用linecache可能会进行不是严格必须的操作。如果这个例程恰好是程序性能瓶颈,可以编写函数,封装循环代码,以获得性能提升。 Python 2.2中代码如下:

def getline(thefilepath, desired_line_number):
    if desired_line_number < 1: return ''
    current_line_number = 0
    for line in open(thefilepath):
        current_line_number += 1
        if current_line_number == desired_line_number: return line
    return ''

参考 See Also

PyCkBk-4-5 (last edited 2009-12-25 07:16:21 by localhost)