【问题标题】:How can I return specific lines in python 2.7 by using f.readline()如何使用 f.readline() 在 python 2.7 中返回特定行
【发布时间】:2014-10-24 01:35:03
【问题描述】:

我正在编写一个程序,它只需要读取文本文件的特定行,比如第 3 行,但我想不出办法。我试过了

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

但是由于某种原因这不起作用。如果有人可以帮助我,那就太好了。

【问题讨论】:

  • “由于某种原因不起作用”——你能说得更具体些吗?您收到索引错误吗?数据有错吗?你怎么知道是错的?等等。事实上,我们只是在猜测问题。

标签: python text-files readlines


【解决方案1】:

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

【讨论】:

  • 是的,谢谢你向我解释,因为我不知道,但我会给 f.readline() 什么论据让我阅读特定的行?再次感谢。
  • @Hanson:如果不知道文件的内容,那将非常困难。不过,我已经针对您的情况发布了一个轻微的解决方法
猜你喜欢
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 1970-01-01
相关资源
最近更新 更多