简体   繁体   中英

How to iterate over every n-th line from a file?

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.

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

I have the following code:

with open('data.txt', 'r') as f:
    for x, line in enumerate(f):
        if x == 3:
            print(line)

In this case it only prints

"This is line four".

I do understand why but how do I take it from here and have it print the lines 4, 7, 10, 13, ...?

The return value of open is an iterator (and thus, iterable), so you can pass it to itertools.islice :

islice(iterable, start, stop[, step]) --> islice object
Return an iterator whose next() method returns selected values from an iterable. [...]

Demo:

data.txt :

line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11
line12
line13

Code:

from itertools import islice

with open('data.txt') as f:
    for line in islice(f, 3, None, 3):
        print line,  # Python3: print(line, end='')

Produces:

line4
line7
line10
line13

In Your code You are printing when x == 3 , so You are printing only the fourth line in a file, because enumeration starts with 0 .

Try:

with open('data.txt', 'r') as f:
    for x, line in enumerate(f):
        if x%3 == 1:
            print(line)

x%3 == 1 means that rest from division x by 3 has to be 1 . This way You will print the lines 1, 4, 7, etc. .

You need to use https://en.wikipedia.org/wiki/Modular_arithmetic

with open('data.txt', 'r') as f:
    for x, line in enumerate(f):
        if x and x % 3 == 0:
            print(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM