我正在编写一个程序,只需要读取文本文件的特定行,比如第3行,但我无法找到一种方法。我试过了
target = open(filename)
lines = target.readlines()
print lines[3]
但由于某种原因,这不起作用。如果有人能帮助我那将是伟大的。
答案 0 :(得分: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