我的示例文件如下:
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
但它只给出了标题。我不知道为什么?
答案 0 :(得分:4)
您缩进了增加i
的部分,因此仅在i == 0
或i == 5
时执行。这意味着i
仅在第一个循环上递增,并且即使在读取第5行时也会永远保持这种状态。
代码应为
i=0
for line in open('test.txt'):
if i == 0 or i == 4:
print(line)
i+=1
当读取第5行时i == 4
,因为计数从0开始。
答案 1 :(得分:3)
您不需要手动增加计数器,最好使用enumerate:
with open('test.txt') as f:
for i, line in enumerate(f):
if i == 0 or i == 4:
print(line)
答案 2 :(得分:2)
作为替代方案,要使用行号访问文件中的行,您还可以使用linecache:
import linecache
print(linecache.getline('test.txt', 1))
print(linecache.getline('test.txt', 5))
答案 3 :(得分:2)
你的代码工作正常只需增加i,if if block
i=0
for line in open('test.txt'):
if i == 0 or i == 4:
print(line)
i +=1
答案 4 :(得分:1)
您的索引定义不正确,有两种类型的for循环:
修复指定间隔的重复循环,而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
查看评论以了解差异。请记住编号从零开始,因此第五行的行号为四。