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

Do I Not Understand the Problem Statement?

  1. Read all the files names in a directory.
  2. Test that all the provided file names are in that directory.

So, I get a list of files in the directory and then make sure each file name is in that list.

I wonder what I'm missing here. I also tried using os.walk to get all files in all sub-directories.

Thanks for any help!

contents.py
import os

def dir_contains(path, file_names):

    files = [f.name for f in os.scandir(path) if f.is_file()]
    for f in file_names:
        if f not in files:
            retun False

    return True

1 Answer

Edited code passes: I didn't type the return keyword correctly.

import os

def dir_contains(path, file_names):
    if not os.path.exists(path):
        return False

    if not os.path.isdir(path):
        return False

    files = [f.name for f in os.scandir(path) if f.is_file()]
    for f in file_names:
        if f not in files:
            return False

    return True