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

标签 python bash filesystems

我目前遇到一个问题,我想获取 n-1 级别的目录列表。该结构看起来有点像下图,我想要一个包含所有蓝色文件夹的列表。然而,树的高度在整个文件系统中是不同的。

enter image description here

由于所有蓝色文件夹的名称通常以字符串 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() 来实现这一点。 os.walk() 返回一个可迭代的三元组(dirnamesubdirectoriesfilenames)。我们可以围绕该输出包装一个列表理解,以仅从文件树中选择“叶”目录 - 只需收集所有没有子目录的 dirnames

import os

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

关于python - 想要使用 bash 或 python 在 n-1 级别(不包含任何子文件夹的文件夹)创建目录列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53384654/

相关文章:

python - git-lint pylint 没有运行 pylintrc 文件

python - 无法使用 MSVC2015 编译 boost.python 1.65.1

bash - 在 Windows 7 的 cygwin 中运行 bash 脚本

python - 使用 pandas 分析超过 20G 的数据帧,内存不足,指定 chunksize 时仍然无法正常工作

python - 将参数作为坐标传递

bash - FFMPEG - 尝试连接多个带和不带音频的文件时出错

r - 如何从 R 中运行多命令 Linux shell 脚本?

php - 不使用 scandir() 或 readdir 映射文件系统

java - 仅包含实时 lucene 索引的目录中的可用磁盘减少

c - fsync 和 syncfs 有什么区别?