Reputation: 855
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?
Upvotes: 1
Views: 12780
Reputation: 1466
you can do this using os
also:
import os
extensions = ('.txt') #extinctions want to search
exclude_directories = set(['exclude_directory_name']) #directory (only names) want to exclude
for dname, dirs, files in os.walk('/root/path/to/directory'): #this loop though directies recursively
dirs[:] = [d for d in dirs if d not in exclude_directories] # exclude directory if in exclude list
for fname in files:
if(fname.lower().endswith(extensions)): #check for extension
fpath = os.path.join(dname, fname) #this generate full directory path for file
print fpath
Upvotes: 8
Reputation: 90
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]
Upvotes: 2