SPYBUG96
SPYBUG96

Reputation: 1117

Nested loops not getting desired output

I'm trying to get this nested loop to work for a bigger program. This is just a small portion of my code

I want my program to match a file name in a folder to a file name in a text document, and if they match do something. I have no clue why the following nested loop is not working.

allGood = open("allGood.txt", "r")
folder = "C:\your\folder\path\here"

for item in allGood:
    for file in os.listdir(folder):

        if file == item:
            print "in item loop" + item
            print "Do a thing"
    print "1 loop completed"

The contents of "allGood.txt"

document10080.pdf
document10098.pdf
document10119.pdf
document10172.pdf
document10178.pdf
and so on

The problem is when it gets to the IF statement. It should match only once per loop, but it doesn't. I am only getting a huge output of "1 loop completed"

Output from inserting print(file, item)

('document10486.pdf', 'document10080.pdf\n')
('document10487.pdf', 'document10080.pdf\n')
('document10488.pdf', 'document10080.pdf\n')
('document10489.pdf', 'document10080.pdf\n')
('document1049.pdf', 'document10080.pdf\n')

I see my problem now

Upvotes: 1

Views: 68

Answers (2)

Prune
Prune

Reputation: 77880

Remember, allGood is a file handle, not the file contents. Perhaps what you need is something like this:

folder = os.listdir("C:\your\folder\path\here")

with open("allGood.txt", "r") as allGood:
    for line in allGood:
        line = line.strip()
        if line in folder:
        ...

Upvotes: 2

Don Question
Don Question

Reputation: 11624

I don't have enough reputation to comment, so i'll try an answer with insufficient informations. Basically you never have a match. That's why you never enter the second loop.

Did you consider handling the filenames as sets?:

real_files = set(os.listdir(folder))
good_files = set(open("allGood.txt", "r").readlines())

matching_files = good_files.intersection(real_files)
for file in matching_files:
    pass # do something

Also the text-file entries may contain white-spaces; consider using 'strip`, e.g:

import string
...
good_files = set(map(string.strip, open("allGood.txt", "r").readlines()))
...

or somewhat less "Perl-ish" ;-)

...
good_files_raw = open("allGood.txt", "r").readlines()
good_files = set(map(string.strip, good_files_raw))
...

Upvotes: 3

Related Questions