How to iterate over every n-th line from a file?
-
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, …? -
Demo:
data.txt:
line1 line2 line3 line4 line5 line6 line7 line8 line9 line10 line11 line12 line13Code:
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
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login


ue