Question

I have the following function currently:

def create_image_list(directory):

    extensions = ('.jpg', 'jpeg', '.png', '.bmp')
    file_list = []

    for root, directories, files in os.walk(directory):
        for filename in files:
            if filename.endswith(extensions):
                filepath = os.path.join(root, filename)
                file_list.append(filepath)

Which goes through every file and subdirectory in a given directory and puts the full path to any files with the given extensions in the list. However, I would like to ignore certain subdirectories, such as those labelled thumbs. How would I go about this?

Était-ce utile?

La solution

You can filter your directories object inside the for loop. To quote the docs

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again.

So something like

for root, directories, files in os.walk(directory):
    directories[:] = [d for d in directories if d not in ['thumbs']]
    for filename in files:
        if filename.endswith(extensions):
            filepath = os.path.join(root, filename)
            file_list.append(filepath)

To ignore other directories, you would add their names to the ['thumbs'] list.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top