gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:20:19 27 4
gpt4 key购买 nike

我正在编写一个程序,只需要读取文本文件的特定行,例如第 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com