首页 > 解决方案 > 在Python中获取特定层的子文件夹名称

问题描述

对于testWindows 环境下以子目录结构命名的文件夹,如下所示:

├─a
│  ├─a1
│  ├─a2
│  └─a3
│      ├─a3_1
│      ├─a3_2
│      └─a3_3
├─b
│  ├─b1
│  ├─b2
│  ├─b3
│  └─b4
└─c
    ├─c1
    ├─c2
    └─c3

我想获取第二层的子文件夹的名称并将它们保存在lista1, a2, a3, b1, b2, b3, b4, c1, c2, c3...

base_dir = r"..\test"

for root, dirs, files in os.walk(base_dir):
    print(root)

输出:

..\test
..\test\a
..\test\a\a1
..\test\a\a2
..\test\a\a3
..\test\a\a3\a3_1
..\test\a\a3\a3_2
..\test\a\a3\a3_3
..\test\b
..\test\b\b1
..\test\b\b2
..\test\b\b3
..\test\b\b4
..\test\c
..\test\c\c1
..\test\c\c2
..\test\c\c3

更新:我尝试split通过反斜杠使用该方法并保存到mylist

base_dir = r"..\test"
mylist = []

**Method 1:**
for root, dirs, files in os.walk(base_dir):
    li = root.split('\\')
    #Only if the list has 3 elements of more, get the 3rd element
    if len(li) > 3:
        #print(li[3])
        mylist.append(li[3])
        #print(mylist)
mylist = list(set(mylist))
mylist.sort()
print(mylist)

**Method 2:**        
for root, dirs, files in os.walk(base_dir):
    try:
        li = root.split('\\')
        mylist.append(li[3])
    except IndexError:
        pass
mylist = list(set(mylist))
mylist.sort()
print(mylist)

输出:

['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3']

现在可以了,谢谢

标签: pythonsplitoperating-systemos.walk

解决方案


当没有子目录时会出现索引错误[2](例如,类似C:\\SomeEmptyFolder

这应该可以正常工作

for root, dirs, files in os.walk(base_dir):
    try:
        print(root.split('\\')[2])
    except IndexError:
        pass

推荐阅读