Get next string in array of string in python

Viewed 54

I have the following code:

lines = []
with open('myfile.txt') as file:
    lines = file.readlines()

line_iter = iter(lines)
for line in line_iter:
    pos = line.find("/")
    if pos == 6:
        str = line[0:5]
        str = str.strip()
        match str:
            case "CASE1":
                editedLines.append(line)
            case "CASE2":
                editedLines.append(line)
            case "CASE3":
                editedLines.append(line)

in CASE3 I want to add the next lines until I see the CASE3_END How can I get the next line in lines array (in other words skipping a couple of lines from the main for loop)

2 Answers

You can pop more lines out of the iterator with next(line_iter), it will raise a StopIteration exception if you try to get more after it's "empty".

For example this works:

lines = [ 1,2,3,4,5,6,7,8 ]
line_iter = iter(lines)
for line in line_iter:
    print(line, next(line_iter))

will print out:

1 2
3 4
5 6
7 8

So you can see it's possible to "pump out" items from the iterator in the middle of the loop.

One way to do this would be to convert the for loop to a while loop and manually iterate through the lines:

line_num = 0
while line_num < len(lines):
    line = lines[line_num]
    pos = line.find("/")
    if pos == 6:
        str_ = line[0:5]
        str_ = str_.strip()
        match str_:
            case "CASE1":
                editedLines.append(line)
            case "CASE2":
                editedLines.append(line)
            case "CASE3":
                while line_num < len(lines) and line != "CASE3_END":
                    editedLines.append(line)
                    line_num += 1
                    line = lines[line_num]
    line_num += 1
Related