I am working on a backup script in Python, and would like it to be able to ignore folders. I therefore have a list of folders to be ignored, ie ['Folder 1', 'Folder3']
. I am using os.walk
, and am trying to get it to skip any folder in the ignored folders list or that has any of the ignored folders as a parent directory. Has anyone done this before, as examples I've seen don't seem to work and often end up creating an empty folder?

- 45,586
- 12
- 116
- 142

- 2,252
- 4
- 29
- 53
-
See this answer http://stackoverflow.com/questions/925056/a-python-walker-that-can-ignore-directories/925291#925291 – Fredrik Pihl Jun 01 '11 at 11:07
2 Answers
From the docs:
When topdown is
True
, the caller can modify the dirnames list in-place (perhaps usingdel
or slice assignment), andwalk()
will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to informwalk()
about directories the caller creates or renames before it resumeswalk()
again.
So, iterate through your list and remove entries that match.

- 776,304
- 153
- 1,341
- 1,358
After the following statement
folders = [path+'/'+dir for (path,dirs,files) in os.walk(base)
for dir in dirs
if dir not in ['Folder 1', 'Folder3', ...]]
the variable folders
should contain the folders you are interested in.
Edit1: ... + '/' + ...
works just in Unix-like OS. I think there is a os.path.join
which does the same job platform indepentently
Edit2: If you want to exclude all Subdirectories of the directories to be excluded, you can try the following:
exclusions = ['Folder 1', 'Folder3', ...]
folders = [path+'/'+dir for (path,dirs,files) in os.walk(base)
if not any([f in path for f in exclusions])
for dir in dirs
if dir not in exclusions
]

- 4,830
- 1
- 25
- 38