Skip to main content
 首页 » 编程设计

python之在python中读取特定行数

2025年05月04日12haluo1

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

#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 
.. 
.. 

请您参考如下方法:

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

请注意,我更改了您的 file.readlines() 以去除尾随换行符。

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

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()