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

How to check if file names exist in a directory list?

Not sure how to think about this. The video was not quite helpful as is many of the Python videos and challenges.

import os

def dir_contains(path, list):
    path_contents = os.listdir(path)
    file_names = list(os.scandir())
    if  path_contents == file_names:
        return True
        return False

2 Answers

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi there, Taylor Fritz! You have a few things going on here. First, you've used a Python keyword as a parameter. You've used list but that word is reserved by Python. We're taking a list of files. The path_contents is fine as it is. What we want to do is loop through the file list that was sent to us. If any one of those files is not in the path_contents we should return False as it wasn't found. If it makes it through the entire list and never hits that return False then it means it never ran into a file that wasn't found in that directory. Remember that any time a return is hit, the function will cease execution right then and not evaluate anything further.

import os

def dir_contains(path, file_names):  # I changed list to another variable name
    path_contents = os.listdir(path)  # this is the contents of the directory   
    for file in file_names:  # loop through the file names
        if file not in path_contents:  # if it didn't find the file in the directory
            return False  #return false
    return True # if it makes it through the entire list and all of them were found

Hope this helps! :sparkles:

Thank you for your help with this Jennifer! And thank you for explaining the goal. It makes sense, how you explained! :)