仅从文件中获取选定的行

Get only selected lines from a file

我有这样的示例文件:

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

我想要 header 和第 5 行。我这样做:

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

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

您已经缩进了递增 i 的部分,因此它仅在 i == 0i == 5 时执行。这意味着 i 仅在第一个循环中递增,并且永远保持这样,即使在读取第 5 行时也是如此。

代码应该是

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

其中 i == 4 当读取第 5 行时,因为从 0 开始计数。

作为替代方案,要使用行号访问文件中的行,您还可以使用 linecache:

import linecache
print(linecache.getline('test.txt', 1))
print(linecache.getline('test.txt', 5))

您不需要手动递增计数器,最好使用 enumerate:

with open('test.txt') as f:
    for i, line in enumerate(f):
        if i == 0 or i == 4:
            print(line)

你的代码工作正常,只是在 if 块之外递增 i

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

你的索引定义不当,有两种for循环:

  1. 固定重复
  2. Foreach 循环

指定间隔的固定重复循环,而 foreach 循环遍历集合。其次,您必须将文件解析为行列表。请尝试以下两种方法之一:

固定重复:

test = open('test.txt').readlines() # file as list of strings

for index in range(len(test)): # iterate according to the number of lines
    if index == 0 or index == 4: # if line number is 0 or 4
        print(test[line]) # print the line at the line number

Foreach 循环

test = open('test.txt').readlines() # file as list of strings

for line in test: # for every line in the list of lines
    index = test.index(line) # find the line's line number
    if index == 0 or index == 4: # if the line number is 0 or 4
        print(line) # print the line

查看评论以了解差异。请记住编号从零开始,因此第五行的行号为四。