Search code examples
pythonpython-3.xglob

Python List all Files in Subdirectories but exclude some Directories


I want to list all txt Files in a Directory Structure but exclude some specific folders.

For example I want to get all txt Files under

D:\_Server\<subfolders>\Temp_1\Config\ or

D:\_Server\<subfolders>\Temp_1\Config\Stat but exclude

D:\_Server\<subfolders>\Temp_1\Config\Historie\ and

D:\_Server\<subfolders>\Temp_1\Config\Archive\

To get all Files I used the following code:

glob.glob('D:\\_Server\\**\\Config\\**\\*.olc', recursive=True)

This results in a List of all txt Files also those in the Archive and Historie Folder.

Is this possible with the Python Glob Module? Or is there a better solution to archive this?


Solution

  • You could just filter your result list, for example with a list comprehension:

    allResults = glob.glob('D:\\_Server\\**\\Config\\**\\*.olc', recursive=True)
    filteredResults = [r for r in allResults if not "Archive" in r and not "Historie" in r]