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

Create a function named dir_contains takes a path to a directory and a list of file names. If all of the file names exis

Create a function named dir_contains takes a path to a directory and a list of file names. If all of the file names exist within that directory, return True, otherwise, return False.

To begin, the syntax of the question is question is horrible. i think there's a "that" missing after dir_contains. and how would i know if all files are there if i don't know what there is. all files means many and how do i know if there are two or 2000 files. just a stupidly phrased question.

but i am stumped beyond belief. the videos gave me no clue and i've searched everywhere for an answer. i answered every other question and simply have no clue.

contents.py
import os
def dir_contains(start):
    files = list(os.listdir(start))
    if files(start).is_file():
        return True
    else:
        return False

3 Answers

Hi ! You need to add a second parameter (the list of file names you want to check) and we need to iterate over all those file names in order to check if they are contained in the directory passed as first parameter, here is a solution to your problem :

import os
def dir_contains(dir_path, file_names):
    dir_files = list(os.listdir(dir_path))
    for file_name in file_names:
        if file_name not in dir_files:
            return False
    return True

thank you!

Rahul Saini
Rahul Saini
4,611 Points

You can use this one.

def dir_contains(d,l):
    for f in l:
        if not os.path.exists(os.path.join(d,f)):
            return False
    return True