如何遍历文件的第n行? [英] How to iterate over every n-th line from a file?
问题描述
首先,我是Python的新手,确实可以找到答案,但是没有运气.到目前为止,我发现的内容只返回一行,就像下面的代码一样.我尝试了其他解决方案,例如 itertools.islice
,但始终只能返回一行.
First, I am new to Python and did search for answers, but no luck. So far what I found only returns a one line like my code below. I tried other solutions like itertools.islice
but always only get a one line back.
我有一个名为 data.txt
的文件,其中包含数据行:
I have a file called data.txt
containing lines of data:
This is line one
This is line two
This is line three
This is line four
This is line five
This is line six
This is line seven
...
我有以下代码:
with open('data.txt', 'r') as f:
for x, line in enumerate(f):
if x == 3:
print(line)
在这种情况下,它仅打印
In this case it only prints
这是第四行".
我确实理解为什么,但是如何从这里拿走它并打印第4、7、10、13,...行?
I do understand why but how do I take it from here and have it print the lines 4, 7, 10, 13, ...?
推荐答案
islice(可迭代,开始,停止[,步骤])->islice对象
返回一个迭代器,该迭代器的next()方法从可迭代的.[...]
islice(iterable, start, stop[, step]) --> islice object
Return an iterator whose next() method returns selected values from an iterable. [...]
演示:
data.txt
:
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11
line12
line13
代码:
from itertools import islice
with open('data.txt') as f:
for line in islice(f, 3, None, 3):
print line, # Python3: print(line, end='')
产生:
line4
line7
line10
line13
这篇关于如何遍历文件的第n行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!