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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With