Jeremy Cox
Jeremy Cox

Reputation: 61

Python 3.5 - Startswith() in if statement not working as intended

I'm working through some easy examples and I get to this one and can not figure out why I am not getting the desired result for loop2. Loop 1 is what I am using to see line by line what is happening. The curious thing is at line 1875, the startswith returns a true (see in loop 1) yet it does not print in loop 2.

Clearly I am missing something crucial. Please help me see it.

Text file can be found at: http://www.py4inf.com/code/mbox-short.txt

xfile = open("SampleTextData.txt", 'r')

cntr = 0
print("Loop 1 with STEPWISE PRINT STATEMENTS")
for line in xfile:
    cntr = cntr + 1
    if cntr >1873 and cntr < 1876:
        print(line)
        print(line.startswith('From: '))
        line = line.rstrip()
        print(line)
        print(cntr)
        print()



print("LOOP 2")
for line in xfile:
    line = line.rstrip()
    if line.startswith('From: '):
        print(line)

Upvotes: 1

Views: 1628

Answers (3)

Vikas Ojha
Vikas Ojha

Reputation: 6950

Before starting the loop 2 you are not closing and re-opening the file. A file is read from starting to end. After loop 1 is completed the read cursor is already at the end of the file and hence nothing left for loop 2 to loop.

Upvotes: 0

unutbu
unutbu

Reputation: 879691

A file object such as xfile is a one-pass iterator. To iterate through the file twice, you must either close and reopen the file, or use seek to return to the beginning of the file:

xfile.seek(0)

Only then will the second loop iterate through the lines of the file.

Upvotes: 4

Patrick Maupin
Patrick Maupin

Reputation: 8137

Your open file is an iterator that is exhausted by the first loop.

Once you loop through it once, it is done. The second loop will not execute, unless you close and re-open it.

Alternatively, you could read it into a string or a list of strings.

Upvotes: 2

Related Questions