Skip to content
Advertisement

Reading next line of big text file

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

with open(input) as infile:
    for line in infile:
        print("current line: ",line)
        #reading next line
        print("this is the second line ", line)
        #jumping back to the beginning and working with the 3rd line

When my text looks like this.

1st line
2nd line
3rd line
4th line
5th line
6th line
7th line

I want the output to be like this

current line: 1st line
this is the second line: 2nd line
current line: 3rd line
this is the second line: 4th line
...

Advertisement

Answer

You can do this using an iter() and next().

with open('text.txt') as infile:
    iterator = iter(infile)
    for line in iterator:
        print("current line:",line)
        print("this is the second line", next(iterator, "End of File"))

Given the input file:

A
B
C
D
E

it outputs:

current line: A
this is the second line B
current line: C
this is the second line D
current line: E
this is the second line End of File
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement