Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read every fourth line in Python

Tags:

python

I have a file where I am trying to read (and write to another file) every fourth line. The solution I'm using doesn't give the desired outcome.

sample.txt line1 line2 line3 line4 line5 line6 line7 line8 line9 line10

script.py

from itertools import islice
with open('sample.txt') as fin, open('output.txt','w') as fout:
         fout.writelines(islice(fin,None,None,4))

Now the output file gives me line1, line5, line9 instead of line4, line8.

How would I go about altering this to get the desired outcome?

like image 909
lenhun Avatar asked Dec 12 '25 13:12

lenhun


1 Answers

You're almost there. islice comes with a start parameter. In your case, it's the second one, that you've set to None. Try this:

fout.writelines(islice(fin,3,None,4)) # line with index 3 is the fourth line
like image 170
Carsten Avatar answered Dec 14 '25 02:12

Carsten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!