-2

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
...
Wessel van Lit
  • 83
  • 1
  • 11
noah1400
  • 1,282
  • 1
  • 4
  • 15
  • did you run your code? what happens? – Psytho Jun 17 '21 at 11:54
  • @Psytho The code I posted always outputs the same line until the for loop starts over, which is logical. I have commented what I want in the code – noah1400 Jun 17 '21 at 11:58
  • 1
    So you basically want to loop through 2 lines at once? 1-2, 3-4 (always pairs)... or 1-2, 2-3 (always previous and current)...? – h4z3 Jun 17 '21 at 12:00
  • 1
    https://stackoverflow.com/questions/1657299/how-do-i-read-two-lines-from-a-file-at-a-time-using-python Here is how to always loop in pairs (1-2, 3-4, 5-6...) - I'd recommend second answer, with itertools. – h4z3 Jun 17 '21 at 12:03
  • 1
    Does this answer your question? [How do I read two lines from a file at a time using python](https://stackoverflow.com/questions/1657299/how-do-i-read-two-lines-from-a-file-at-a-time-using-python) – h4z3 Jun 17 '21 at 12:04
  • @h4z3 I want it to be possible to read in the next line three times or four times. For example `jumpToNextLine() if line == "3rd line"`. – noah1400 Jun 17 '21 at 12:09
  • I don't understand. Do you want to read a variable number of lines each time? Then top answer from the linked question is actually good as you just do `while True` and get lines inside the loop – h4z3 Jun 17 '21 at 12:15

1 Answers1

1

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
Wessel van Lit
  • 83
  • 1
  • 11