如何跳转到巨大文本文件中的特定行? [英] How to jump to a particular line in a huge text file?
问题描述
是否有以下代码的替代方案:
Are there any alternatives to the code below:
startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
如果我正在处理一个巨大的文本文件 (~15MB)
,其中包含未知但长度不同的行,并且需要跳转到我事先知道的特定行?当我知道我至少可以忽略文件的前半部分时,我通过一个一个地处理它们而感到难过.如果有的话,寻找更优雅的解决方案.
If I'm processing a huge text file (~15MB)
with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.
推荐答案
linecache
模块允许从 Python 源文件中获取任何行,同时尝试使用缓存进行内部优化,这是从单个文件中读取多行的常见情况.这由 traceback
使用用于检索源行以包含在格式化回溯中的模块...
The
linecache
module allows one to get any line from a Python source file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file. This is used by thetraceback
module to retrieve source lines for inclusion in the formatted traceback...
这篇关于如何跳转到巨大文本文件中的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!