DEAR PEOPLE FROM THE FUTURE: Here's what we've figured out so far...

Welcome! This is a Q&A website for computer programmers and users alike, focused on helping fellow programmers and users. Read more

What are you stuck on? Ask a question and hopefully somebody will be able to help you out!
0 votes

The test is failing because it's getting the files from hidden folders too. How can I modify the code so that it skips the hidden folders?

def get_files_not_in_hidden_folder(parent_folder: str, extension: str) -> List[str]:
    """
    Get all files recursively from parent folder,
    except for the ones that are in hidden folders
    """
    files = []
    for root, _, filenames in os.walk(parent_folder):
        for filename in filenames:
            if filename.endswith(extension) and not root.startswith('.'):
                files.append(os.path.join(root, filename))
    return files

def test_get_files_not_in_hidden_folder():
    Path('tmp').mkdir(parents=True, exist_ok=True)
    Path('tmp/test.json').touch()
    Path('tmp/tmp/.tmp').mkdir(parents=True, exist_ok=True)
    Path('tmp/tmp/.tmp/test.json').touch()
    Path('tmp/.tmp/tmp').mkdir(parents=True, exist_ok=True)
    Path('tmp/.tmp/tmp/test.json').touch()

    assert get_files_not_in_hidden_folder('tmp', '.json') == ['tmp/test.json']

    shutil.rmtree(Path('tmp'))
by
edited by

1 Answer

0 votes
 
Best answer
for root, subdirs, filenames in os.walk(path):
    subdirs[:] = [d for d in subdirs if not d[0] == '.']
    for filename in filenames:
        if filename.endswith(extension):
            files.append(os.path.join(root, filename))

for root, _, filenames in os.walk(parent_folder):
        for filename in filenames:
            if filename.endswith(extension) and not os.path.basename(root).startswith('.'):
                files.append(os.path.join(root, filename))

for root, _, filenames in os.walk(parent_folder):
        for filename in filenames:
            if filename.endswith(extension) and "/." not in root:
                files.append(os.path.join(root, filename))

https://stackoverflow.com/a/13454267/19924240

by
selected by
Contributions licensed under CC0
...