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

Want to create a list of directories at the n-1 level (folders that do not contain any subfolders) with either bash or python

我目前遇到一个问题,我想获取 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] + '/')

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

所以另一种陈述问题的方式是您想要所有不包含子文件夹的文件夹?如果是这种情况,那么您可以利用 os.walk 列出文件夹中所有子文件夹的事实。如果该列表为空,则将其附加到 dirList

import os
import sys

def getDirList(dir):
    # x[1] contains the list of subfolders
    dirList = [(x[0], x[1]) for x in os.walk(dir)]
    return dirList

oldDirList = getDirList(sys.argv[1])

dirList = []

for i, dir in enumerate(oldDirList):
    if not dir[1]:    # if the list of subfolders is not empty
        dirList.append(dir[0])

print dirList

换句话说,我想你在问什么 - 你想列出所有不包含任何子文件夹的文件夹(因此只包含非文件夹文件)。

您可以很容易地使用 os.walk()os.walk() returns 可迭代的三元组 (dirnamesubdirectoriesfilenames)。我们可以围绕该输出将列表推导包装到 select 只有文件树中的 "leaf" 目录 - 只需收集所有没有子目录的 dirnames

import os

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

今天我遇到了类似的问题。

尝试路径库:https://docs.python.org/3/library/pathlib.html

from pathlib import PurePath
import os, sys

#os.getcwd() returns path of red_dir if script is inside
gray_dir = PurePath(os.getcwd()).parents[1]  # .parents[1] returns n-1 path 
blue_things = os.listdir(gray_dir)


blue_dirs = []
for thing in blue_things:
    if os.path.isdir(str(gray_dir) + "\" + str(thing)):  # make sure not to append files
        blue_dirs.append(thing)

print(blue_dirs)