In my application, the user may or may not want to ignore some directories. I can do that, but it seems like I am repeating myself. Does anyone have an idea to refactor that?
from os import walk, path exclude = ['dir1/foo'] for root, dirs, files in walk('.', topdown=True): if exclude != None: dirs[:] = [d for d in dirs if d not in exclude] for name in files: for excluded in exclude: if excluded not in root: print path.join(root, name) else: for name in files: print path.join(root, name)
None when there are no dirs to exclude. I thought of setting it to an empty list, but then, this loop
for excluded in exclude: won't execute at all. My ambition was to avoid such a big
else. Any ideas?
gsamaras@pc:~/mydir$ ls */* dir1/bar: test.txt dir1/foo: test.txt dir2/bar: test.txt dir2/foo: test.txt
I am getting:
If I want, I can do an
exclude = ['foo'], and then get:
meaning that I ignored all directories named "foo".