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

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.

contents.py
import os

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

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
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! :)