This is just a simplified version of Charles Menguy's solution, and I'm only adding it as an answer because it was hard to read as a comment. But here's the key:
First, use grouper
from the itertools
recipes to group the file into groups of 6 lines:
groups = grouper(6, f)
Next, you can throw out every other line just by slicing:
nonblank = [group[::2] for group in groups]
Or, alternatively, by filtering out the blank lines explicitly:
nonblank = [filter(bool, group) for group in groups]
If you need to strip each line, you can either use a list comprehension, or map
. Generally, I prefer map
if I don't need to lambda/partial up a new function, and here we don't; it's just map(str.strip, group)
.
Putting it together, here's the whole thing, as a one-liner (which I think is still pretty readable):
with open('input.txt') as f:
arr = [map(str.strip, group[::2]) for group in grouper(6, f)]