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)
exclude
is 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 if
/else
. Any ideas?
Example:
gsamaras@pc:~/mydir$ ls */*
dir1/bar:
test.txt
dir1/foo:
test.txt
dir2/bar:
test.txt
dir2/foo:
test.txt
I am getting:
./dir2/foo/test.txt
./dir2/bar/test.txt
./dir1/bar/test.txt
If I want, I can do an exclude = ['foo']
, and then get:
./dir2/bar/test.txt
./dir1/bar/test.txt
meaning that I ignored all directories named "foo".
foo
andbar
) for this? \$\endgroup\$