Nested loops not getting desired output

时间:2017-11-08 22:05:11

标签: python python-2.7 loops nested

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

2 个答案:

答案 0 :(得分:3)

我没有足够的声誉来评论,所以我会尝试一个信息不足的答案。基本上你永远不会有比赛。这就是你永远不会进入第二个循环的原因。

您是否考虑将文件名视为集合?:

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

文本文件条目也可能包含空格;考虑使用' strip`,例如:

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

或者更少" Perl-ish" ; - )

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

答案 1 :(得分:2)

请记住,allGood是文件句柄,而不是文件内容。也许你需要的是这样的东西:

exec()