Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
231,072 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```