0

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?

taskinoor
  • 45,586
  • 12
  • 116
  • 142
Dean Barnes
  • 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 Answers2

2

From the docs:

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() 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 inform walk() about directories the caller creates or renames before it resumes walk() again.

So, iterate through your list and remove entries that match.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

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
          ]
phynfo
  • 4,830
  • 1
  • 25
  • 38