开发者

How to refine list of directories to remove subdirectories of newly added directory

开发者 https://www.devze.com 2023-03-30 06:45 出处:网络
I have a list 开发者_如何学编程of directories, eg: direc_list = [r\'C:\\test\', r\'C:\\test2\\subdir\']

I have a list 开发者_如何学编程of directories, eg:

direc_list = [r'C:\test', r'C:\test2\subdir']

I then want to add another directory to the list

new_direc = r'C:\test2'

How can I correctly remove any subdirectories of this new directory in my list?

After adding r'C:\test2' my output should be so that

direc_list
>>> [r'C:\test', r'C:\test2']

I was trying this using the in operator,

for direc in direc_list:        
    if new_direc in direc:
        direc_list.remove(direc)

but this fails because the word 'test' is a substring of 'test2'


Use str.startswith() as in:

for direc in direc_list:
    if direc.startswith(new_direc):
        dir_list.remove(direc)

Depending upon input, might want to check out something like, os.path.abspath(path) to normalize your paths so they match up better.


Maybe simply add an path seperator after the path.

import os
for direc in direc_list:        
    if direc.startswith(new_direc + os.sep):
        dir_list.remove(direc)
0

精彩评论

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