I am working on a backup script in Python, and would like it to be able to ignore folders. I theref开发者_Python百科ore 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?
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.
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
]
精彩评论