Python-如何跳至巨大文本文件中的特定行?

发布于 2021-02-02 23:12:45

以下代码是否有替代方法:

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),其行数未知但长度不同,并且需要跳转到特定行我应该事先知道哪个号码?当我知道我至少可以忽略文件的前半部分时,我很难一一处理它们。寻找更优雅的解决方案(如果有)。

关注者
0
被浏览
64
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    由于你不知道换行符在哪里,因此无法至少一次不读入文件就无法跳转。你可以执行以下操作:

    # Read in the file once and build a list of line offsets
    line_offset = []
    offset = 0
    for line in file:
        line_offset.append(offset)
        offset += len(line)
    file.seek(0)
    
    # Now, to skip to line n (with the first line being line 0), just do
    file.seek(line_offset[n])
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看