Reputation: 23
Say I have a text file(test.txt) with the following lines
line0
line1
line2
line3
line4
line5
line6
line7
line8
line9
It's easy to iterate over it
fh=open("./test.txt")
for x in fh:
print(x)
fh.close()
What I'm trying to do is print lines 2 lines, like this,
line0
line2
line1
line3
So essentially I'm trying to access the current line and the a line 2 lines down from the current location. I have been messing around with the itererator but not got anywhere. I'd welcome all input please. Thanks
Upvotes: 1
Views: 443
Reputation: 46849
also an option which does not read the whole file in one go but just stores 2 lines at a time:
txt = """line0
line1
line2
line3
line4
line5
line6
line7
line8
line9"""
with StringIO(txt) as file:
a, b = next(file), next(file)
for c in file:
print(a, end='')
print(c, end='')
a, b = b, c
with the output
line0
line2
line1
line3
line2
line4
line3
line5
line4
line6
line5
line7
line6
line8
line7
line9
you'd have to replace the StringIO
part with your file of course.
Upvotes: 0
Reputation: 177664
Here is a generator that handles any number of lines including odd length files:
def alternate(f):
write = False
for line in f:
if not write:
keep = line
else:
yield line
yield keep
write = not write
if write: # handle odd-line-count files.
yield line
with open('test.txt') as f:
for line in alternate(f):
print(line,end='')
Example input (odd length):
line0
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
Output:
line1
line0
line3
line2
line5
line4
line7
line6
line9
line8
line10
Upvotes: 0
Reputation: 106553
You can use itertools.tee
to replicate the file iterator, skip the first two values of the second iterator returned by tee
, and then zip
the two iterators to produce the desired pairs of lines so that you can chain
and join
them for output:
from itertools import tee, chain
l, n = tee(fh)
next(n)
next(n)
print(''.join(chain.from_iterable(zip(l, n))))
With your sample input, this outputs:
line0
line2
line1
line3
line2
line4
line3
line5
line4
line6
line5
line7
line6
line8
line7
line9
Upvotes: 0
Reputation: 392
and Welcome to Stackoverflow
You can try this.
left = next(fh)
center = next(fh)
while True:
try:
right = next(fh)
except StopIteration:
break
print('{}\n{}'.format(left, right)
left = center
center = right
This returns
line0
line2
line1
line3
line2
line4
line3
line5
and so on...
Upvotes: 1
Reputation: 2615
The easiest way would be to just read the whole file:
fh = open("./test.txt")
lines = fh.readlines()
for i in range(len(lines) - 2):
print(lines[i])
print(lines[i + 2])
Upvotes: 2