想要使用bash或python创建n-1级别的目录列表(不包含任何子文件夹的文件夹)

Sha*_*ala 5 python filesystems bash

我目前有一个问题,我想获得一个n-1级别的目录列表.结构看起来有点像下图,我想要一个蓝色的文件夹列表.但是,树的高度在整个文件系统中是不同的.

在此输入图像描述

由于所有蓝色的文件夹通常以字符串结尾images,我在Python下面编写了代码:

def getDirList(dir):
    dirList = [x[0] for x in os.walk(dir)]
    return dirList

oldDirList = getDirList(sys.argv[1])

dirList = []

# Hack method for getting the folders
for i, dir in enumerate(oldDirList):
    if dir.endswith('images'):
        dirList.append(oldDirList[i] + '/')
Run Code Online (Sandbox Code Playgroud)

现在,我不想使用这种方法,因为我想要一个通用的解决方案,使用Python或者bash脚本,然后将bash脚本结果读入Python.哪一个在实践和理论上更有效?

Gre*_*Guy 4

换句话来说,我认为您要问的是 - 您想列出所有不包含任何子文件夹的文件夹(因此仅包含非文件夹文件)。

你可以os.walk()很容易地使用它。os.walk()返回一个三元组 ( dirname, subdirectories, filenames) 的可迭代对象。我们可以围绕该输出包装一个列表理解,以仅从文件树中选择“叶”目录 - 只需收集所有dirnames没有子目录的目录。

import os

dirList = [d[0] for d in os.walk('root/directory/path') if len(d[1]) == 0]
Run Code Online (Sandbox Code Playgroud)