首先,我是 Python 的新手,确实搜索过答案,但没有成功。到目前为止,我发现只返回一行,如下面的代码。我尝试了其他解决方案,例如 itertools.islice
,但总是只返回一行。
我有一个名为 data.txt
的文件,其中包含几行数据:
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)
在这种情况下它只打印
"This is line four".
我明白为什么,但我如何从这里获取它并让它打印第 4、7、10、13 行,...?
最佳答案
open
的返回值是一个迭代器(因此是可迭代的),因此您可以将它传递给 itertools.islice
:
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
关于python - 如何遍历文件中的每第 n 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36487709/