读取python中的特定行数

Cur*_*ity 1 python data-mining large-data

我有BIG数据文本文件,例如:

#01textline1
1 2 3 4 5 6
2 3 5 6 7 3
3 5 6 7 6 4
4 6 7 8 9 9

1 2 3 6 4 7
3 5 7 7 8 4
4 6 6 7 8 5

3 4 5 6 7 8
4 6 7 8 8 9
..
..
Run Code Online (Sandbox Code Playgroud)

mer*_*011 8

您不需要循环来实现您的目的.只需使用index列表中的函数来获取两行的索引并获取它们之间的所有行.

请注意,我将您更改file.readlines()为剥离尾随换行符.

(file.read().splitlines()如果read()在一行数据中间结束,则使用可能会失败.)

file1 = open("data.txt","r")
file2=open("newdata.txt","w")
lines = [ line.rstrip() for line in file1.readlines() ]

firstIndex = lines.index("#02textline2")
secondIndex = lines.index("#03textline3")

print firstIndex, secondIndex
file2.write("\n".join(lines[firstIndex  + 1 : secondIndex]))


file1.close()
file2.close()
Run Code Online (Sandbox Code Playgroud)