I’m new to python. I have a huge text file (about 15gb), so it is not possible to read in all the lines, I have read here how to fix that problem. Now about my problem. Is it possible to read the next line within a for loop without jumping to the beginning of the loop.
This is what I mean
JavaScript
x
7
1
with open(input) as infile:
2
for line in infile:
3
print("current line: ",line)
4
#reading next line
5
print("this is the second line ", line)
6
#jumping back to the beginning and working with the 3rd line
7
When my text looks like this.
JavaScript
1
8
1
1st line
2
2nd line
3
3rd line
4
4th line
5
5th line
6
6th line
7
7th line
8
I want the output to be like this
JavaScript
1
6
1
current line: 1st line
2
this is the second line: 2nd line
3
current line: 3rd line
4
this is the second line: 4th line
5
6
Advertisement
Answer
You can do this using an iter()
and next()
.
JavaScript
1
6
1
with open('text.txt') as infile:
2
iterator = iter(infile)
3
for line in iterator:
4
print("current line:",line)
5
print("this is the second line", next(iterator, "End of File"))
6
Given the input file:
JavaScript
1
6
1
A
2
B
3
C
4
D
5
E
6
it outputs:
JavaScript
1
7
1
current line: A
2
this is the second line B
3
current line: C
4
this is the second line D
5
current line: E
6
this is the second line End of File
7