【问题标题】:Get specific layer of subfolders' name in Python在 Python 中获取特定层的子文件夹名称
【发布时间】:2019-05-06 13:13:36
【问题描述】:

对于名为test的文件夹,其子目录结构在Windows环境下如下:

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

我想获取第二层的子文件夹的名字并保存在list:a1, 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']

现在可以了,谢谢。

【问题讨论】:

标签: python split operating-system os.walk


【解决方案1】:

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

这应该可以正常工作

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

【讨论】:

    【解决方案2】:

    从您的输出中,很明显 root.split('\\') 并不总是包含 3 个元素,因此 print(root.split('\\')[2]) 抛出索引超出范围,我建议先检查列表的长度,然后获取第 3 个元素

    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) > 2:
            print(li[2])
    

    输出将是

    a
    a
    a
    a
    a
    a
    b
    b
    b
    b
    c
    c
    c
    

    然后根据更新的问题制作您的mylist,您可以先将所有元素附加到 mylist,然后使用itertools.groupby 一次性删除连续的重复项,而不是在每一步都创建一个集合之外的列表

    from itertools import groupby
    
    mylist = []
    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:
            val = li[3].strip()
            #If element is non-empty append to list
            if val:
              mylist.append(val)
    
    #Remove consecutive repeated elements by using groupby
    result = [x[0] for x in groupby(mylist)]
    print(result)
    

    输出将是

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

    【讨论】:

      猜你喜欢
      • 2016-02-16
      • 2016-01-27
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多