如何在Python 2.7中使用f.readline()返回特定行

1 投票
1 回答
745 浏览
提问于 2025-04-18 22:19

我正在写一个程序,需要从一个文本文件中只读取特定的一行,比如说第三行,但我不知道该怎么做。我试过

    target = open(filename)
    lines = target.readlines()
    print lines[3]

但是出于某种原因,这个方法不管用。如果有人能帮我,那就太好了。

1 个回答

3

Python使用的是从0开始的索引。这意味着你文件中的第一行是lines[0],第二行是lines[1],依此类推。
所以,第三行(你想要的那一行)其实是在lines[2],而不是lines[3]

举个例子:

In [78]: lines
Out[78]: ['line1', 'line2', 'line3', 'line4']

In [79]: lines[0]
Out[79]: 'line1'

In [80]: lines[1]
Out[80]: 'line2'

In [81]: lines[2]
Out[81]: 'line3'

如果你只想累积文件中的特定行:

def readSpecificLines(filepath, lines):
    # lines is a list of line numbers that you are interested in. Feel free to start with line number 1
    lines.sort()
    i=0
    answer = []
    with open(filepath) as infile:
        fileReader = enumerate(infile, 1)
        while i<len(lines):
            nextLine = lines[i]
            lineNum, line = next(fileReader)
            if lineNum == nextLine:
                answer.append(line)
                i += 1
    return answer

撰写回答