Search code examples
pythonif-statementstartswith

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)

Solution

  • 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.