开发者

Determining whether a folder is in a file path

开发者 https://www.devze.com 2023-03-09 14:09 出处:网络
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

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 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.


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
          ]
0

精彩评论

暂无评论...
验证码 换一张
取 消