python - 如何使用 f.readline() 返回 python 2.7 中的特定行

标签 python text-files readlines

我正在编写一个程序,只需要读取文本文件的特定行,例如第 3 行,但我无法找到一种方法来做到这一点。我试过了

    target = open(filename)
    lines = target.readlines()
    print lines[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

关于python - 如何使用 f.readline() 返回 python 2.7 中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25578450/

相关文章:

python - 验证前一行是否具有与当前行相同的字符串和另一列的总和值

python - .readlines() 返回空列表(已解决)-> 使用 csv 将数据添加到特定的命名行

python - 解压的值太多,python,findcontours

python - 使用 exec() 将 python 输出转换为字符串变量

python - Eclipse、Python 和 Google SDK

c - 读取文本文件行中特定字符串后面的所有数字

mysql - vb.net 的字典中不存在给定的键

c++ - 将数据文件包含到 C++ 项目中

python - 在文本文件上一次迭代两行,同时在 python 中一次递增一行

python - __setattr__ 方法确保类中的对象不可变