Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python for File Systems Navigation Dir Contents

Help needed with "Create a function named dir_contains " ...

Maybe I'm misunderstanding what this challenge is asking for. My code seems to work from python in my console but does not satisfy the challenge. Error says "Got False for some existing paths"

Here's my code:

import os

def dir_contains(path, flist):
    for root, dirs, files in os.walk(path):
        for file in flist:
            if file in files:
                continue
                return True
        else:
            return False

And this is how I test it:

import os

def dir_contains(path, flist):
    for root, dirs, files in os.walk(path):
        for file in flist:
            if file in files:
                print(file)
                continue
                print("will return true")
                return True
        else:
            print("false: {}".format(file))
            return False

dir_contains("py/bin", ["pip","pip3", "pip3.5", "kkk.txt"])

My py/bin contains pip, pip3, and pip3.5 but does not contain kkk.txt. My result is:

(py) keith@ada:~/code/py$ python test.py 
pip
pip3
pip3.5
false: kkk.txt

Chris Freeman ? Could you help me with this?

Steven Parker ?

1 Answer

Steven Parker
Steven Parker
216,016 Points

:bell: I got your alert.

The instructions say, "If all of the file names exist within that directory, return True, otherwise, return False.". But looking at this loop, it doesn't seem like it can ever return a True:

        for file in flist:
            if file in files:
                continue     # this statement always starts the loop over
                return True  # so this statement will never be executed!
        else:
            return False

But there's also no return after the outer loop finishes. I would expect that would be the place where you'd want to return a True.

Thanks Steven for pointing out that faulty logic, I appreciate your help!

This passed:

import os

def dir_contains(path, flist):
    for root, dirs, files in os.walk(path):
        for file in flist:
            if file not in files:
                return False
        else:
            continue
    return True```