Shi.Bi Shi.Bi - 8 days ago 5
Python Question

reading lines of a file between two words

I have a file containing numbers and 2 words : "start" and "middle"
I want to read numbers from "start" to "middle" in one array and numbers from "middle" to end of the file into another array.
this is my python code:

with open("../MyList","r") as f:
for x in f.readlines():
if x == "start\n":
continue
if x == "middle\n":
break
x = x.split("\n")[0]
list_1.append(int(x))

print list_1

for x in f.readlines():
if x == "middle\n":
continue
list_2.append(int(x))

print list_2


but the problem is that my program never enters second loop and jumps to

print list_2


I searched in older questions but can not figure out the problem.

Answer

Its because you are reading the whole at the 1st loop, when it enter 2nd loop, file pointer is already at end of file and you will get an empty list from f.readlines().

You can fix that either by reopen the file or set the file pointer to the beginning of file again with f.seek(0) before the 2nd for loop

with open("../MyList","r") as f:
    with open("../MyList","r") as f:
        for x in f.readlines():
            # process your stuff for 1st loop

        # reset file pointer to beginning of file again
        f.seek(0)

        for x in f.readlines():
            # process your stuff for 2nd loop

it will be not so efficient by reading whole file into memory if you are processing large file, you can just iterate over the file object instead of read all into memory like code below

list1 = []
list2 = []
list1_start = False
list2_start = False
with open("../MyList","r") as f:
    for x in f:
        if x.strip() == 'start':
            list1_start = True
            continue
        elif x.strip() == 'middle':
            list2_start = True
            list1_start = False
            continue

        if list1_start:
            list1.append(x.strip())
        elif list2_start:
            list2.append(x.strip())

print(list1)
print(list2)
Comments