Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize "for row in file" loop?

Tags:

python

I'm struggling with python's "for" initialization problem. I'd like to detect lacks of numbers in a text file, example:

1001 :foo foo
1002 :foo foo
1004 :foo foo
1006 :foo foo
1007 :foo foo
1008 :foo foo

From this file, lacks of 1003 and 1005 should be detected. And here's my code:

import sys
import os

args = sys.argv
if (len(args) < 4):
    print("Invalid args")

path = args[1]
numstart = int(args[2])
numend = int(args[3])

with open(path, mode='r') as f:
    for numfind in range( numstart, numend ):
        for row in f:
            flag = row.find(str(numfind))
            if (flag != -1):
                print("found: " + str(numfind))
                break
        else:
            print("Not found: " + str(numfind))

I expected to scan f from first row every loop of for row in f but I got like this:

Found: 1001
Found: 1002
Not found: 1003
Not found: 1004
Not found: 1005
Not found: 1006
Not found: 1007
Not found: 1008

And I think there's no iteration of for rows in f loop. This works:

for numfind in range( numstart, numend ):
    with open(path, mode='r') as f:
        for row in f:
            flag = row.find(str(numfind))
            if (flag != -1):
                print("found: " + str(numfind))
                break
        else:
            print("Not found: " + str(numfind))

Yes it works, but this hack is not a good solution.

like image 586
Naoki Nakamura Avatar asked Mar 09 '26 03:03

Naoki Nakamura


1 Answers

You open the file f and then iterate over it (reading it), without resetting the file to the initial position between for loops with f.seek(0). After the first for row in f, f will have no more rows to read, so it essentially becomes a no op (and why you see no iteration). You want:

with open(path, mode='r') as f:
    for numfind in range( numstart, numend ):
        for row in f:
            flag = row.find(str(numfind))
            if (flag != -1):
                print("found: " + str(numfind))
                break
        else:
            print("Not found: " + str(numfind))
        f.seek(0)

The reason your second approach works by opening the file within the loop is that you are re-reading the file from the first line every loop, which is what we achieve by adding the f.seek(0) above.

like image 123
TheoretiCAL Avatar answered Mar 11 '26 16:03

TheoretiCAL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!