Python 仅从文件中获取选定行
我有如下示例文件:Python 仅从文件中获取选定行,python,python-3.x,Python,Python 3.x,我有如下示例文件: 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 ....... 我想要头球和第五线。我这样做: i=0 for line in open('test.txt'): if i == 0 or i == 5: print(line) i+=1 但它只给出了标题。我不
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
.......
我想要头球和第五线。我这样做:
i=0
for line in open('test.txt'):
if i == 0 or i == 5:
print(line)
i+=1
但它只给出了标题。我不知道为什么?您已经缩进了增量
I
的部分,因此它仅在I==0
或I==5
时执行。这意味着i
仅在第一个循环中递增,并且永远保持不变,即使在读取第五行时也是如此
代码应该是
i=0
for line in open('test.txt'):
if i == 0 or i == 4:
print(line)
i+=1
其中,当读取第5行时,由于计数从0开始,因此
i==4
。您已经缩进了增量i
的部分,因此它仅在i==0
或i==5
时执行。这意味着i
仅在第一个循环中递增,并且永远保持不变,即使在读取第五行时也是如此
代码应该是
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))
或者,要使用行号访问文件中的行,也可以使用linecache:
import linecache
print(linecache.getline('test.txt', 1))
print(linecache.getline('test.txt', 5))
您不需要手动递增计数器,最好使用:
您不需要手动递增计数器,最好使用:
您的代码工作正常,只需增加i,超出if块
i=0
for line in open('test.txt'):
if i == 0 or i == 4:
print(line)
i +=1
您的代码工作正常,只需增加i,超出if块
i=0
for line in open('test.txt'):
if i == 0 or i == 4:
print(line)
i +=1
索引定义不正确,有两种类型的for循环:
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
请参阅注释以了解差异。请记住编号从零开始,因此第五行的行号为四。您的索引定义不正确,有两种类型的for循环:
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
请参阅注释以了解差异。请记住编号从零开始,因此第五行的行号为四。请注意linecache的一个潜在问题:它将整个文件读入内存,可能不是实现这一点的最方便内存的方法。是的,但OP并不表示内存有问题,或者文件非常大。这仍然是一个有趣的替代方案,可以代替更直接的“手动”循环;我主要是为了让未来的观众不要用10^9行来评论…;-)请注意linecache的一个潜在问题:它将整个文件读取到内存中,这可能不是实现这一点的最方便内存的方法。是的,但OP没有指出内存是否有问题,或者文件是否非常大。这仍然是一个有趣的替代方案,可以代替更直接的“手动”循环;我主要是为了让未来的观众不要用10^9行来评论…;-)