I have a txt file, there are thousands of lines there, for example:
line 1 test
line 2 test
line 3 test
line 4 test
line 5 test
line 6 test
line 7 test
line 8 test
line 9 test
I wish to read line 1, line 4, line 7, line 10, line 13 ... but ignore line 2, 3, 5, 6, 8, 9.... How can I read these lines?
you can use itertools.islice to iterate with a given step:
for line in itertools.islice(inputFile, None, None, 3):
Note that I'd much prefer to specify step = 3 as a keyword but it seems islice doesn't support that. :(
This is conceptually similar to reading all the lines into memory then taking a slice of the resulting list:
all_lines = inputFile.readlines() #very memory inefficient
for line in all_lines[::3]: #step of 3, start is None and end is None.
However islice, much like everything else in itertools, is very memory efficient.
Okey, I solved the problem by using for i, line in enumerate(inputFile):
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