Skip to main content
 首页 » 编程设计

python之仅从文件中获取选定的行

2025年05月04日9lvdongjie

<分区>

我有这样的示例文件:

h1,h2,h3,h4 #header 
1,2,3,4 
5,6,7,8 
1,2,3,4 
5,6,7,8 # 5th line 
1,2,3,4 
5,6,7,8 
1,2,3,4 
5,6,7,8 
1,2,3,4 
5,6,7,8 
....... 

我想获取标题和第 5 行。我这样做:

i=0 
for line in open('test.txt'): 
    if i == 0 or i == 5: 
        print(line) 
        i+=1 

但它只给出标题。不知道为什么?