开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜