Reputation: 5499
I want to find files of a specific type in a certain directory. The directory has lots and lots of subfolders and I want to ignore certain ones. I am using the following code-
def locate(pattern, root=os.curdir):
'''Locate all files matching supplied filename pattern in and below
supplied root directory.'''
for path, dirs, files in os.walk(os.path.abspath(root)):
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
for filename in locate("*.s2p"):
#do something
I think there should be some way to change os.curdir to os.curdir (minus some folders) , or perhaps I can check current path and put in a conditional loop ? I tried os.cwd() but i got an error message saying 'module' object has no attribute 'cwd'
Upvotes: 2
Views: 1043
Reputation: 24822
If you want to ignore some subdirectories while walking with os.walk
, you can mutate the value of "dirs". E.g.
ignored = ["foo", "bar"]
for path, dirs, files in os.walk(os.path.abspath(root)):
for dir in ignored:
if dir in dirs: dirs.remove(dir)
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
This would skip all subdirectories named "foo" or "bar" while walking the directory tree.
Upvotes: 2