Shaun Shaun - 4 months ago 15
Python Question

is while loop infinite

I'm trying to build a list of inputs from several files. I need the list to consist only of the first file with a given basename. So if I a & b were folders, and there were "C:\a\file1.ext", "C:\b\file1" and "C:\c\file1" and I had a list of names file1, file2 and so on, I would want the script to find file1 in C:\a\file1.ext and then move on to the next name in the list. In some cases file-x.ext may not be in C:\a or C:\c or C:\b.

I'm setting a condition to count the file once it's base name is found in the list. Once the count = 1 it exits the while loop, resets the count to 0, and goes to the next name in the list, adding the first instance only of the file name to a new input list. The code I have seems to keep running so I think I have an internal loop but I thought setting count to 0 outside of the while loop would prevent this:

count = 0
for name in dbfOnlyLst:
for file in fileLst:
while count < 1:
if os.path.basename(file) == name+".dbf":
values.add(file)
count += 1
count = 0
inList = list(values)

Answer

Your while loop will be infinite because it only achieves the exit condition if os.path.basename(file) == name+".dbf" returns True. If it isn't true, then count will never be updated, and the loop will perform the same conditional check over and over again.

os.path.basename(file) just returns the filename without the path -- it doesn't continue on to the next file in your list, so there's no reason why performing that check multiple times will do anything different.

So, you don't really need that while loop at all. You're just trying to check if each file in your fileLst object is equal to the filename you're looking for, so just iterate over fileLst.

And since you want to just record the first match of your base filename, you can use the break keyword to exit your inner loop early, as soon as you find a match. This way you won't keep iterating over fileLst and will move on to the next name in dbfOnlyLst

for name in dbfOnlyLst:
    for file in fileLst:
        if  os.path.basename(file) == name+".dbf":
            values.add(file)
            break # only add the first match
inList = list(values)
Comments