python - 使用 os.walk 在 python 中仅列出所有带有 png 的子目录

标签 python jupyter-notebook directory-structure os.walk ipywidgets

我需要一些提示并帮助解决我的问题。 我想在 jupyter 笔记本中的目录上创建一个下拉菜单。该目录内有带有 png 的目录,以及一些带有带有 png 的子目录的目录。现在我想获得所有包含 png 的目录的列表。但不是里面有 dir´s 的 dir´s。 ATM 我得到了每个目录,但那是错误的,因为我只能使用里面有 png 的目录。这是我的代码 atm:

dir_path = 'Learning set/Calanus hyp/Chyp 1/'
path = 'Learning set/'   

for root, dirs, files in os.walk(path):
    for name in dirs:
        if ([os.path.isfile(os.path.join(path, f)) for f in os.listdir(path)]) == True:
            namelist += [os.path.join(root,name)]

def get_and_plot(b):
    clear_output()
    global dir_path
    dir_path_new=test.value+"/"
    dir_path=dir_path_new
    global counter
    counter=0
    execute()

test.observe(get_and_plot, names='value')

举个例子: 我有目录“Learing Set”并且想要一个下拉菜单。但下拉菜单显示了目录 Bubble、Bubble1、Bubble2 等。目录 BubbleX 里面有 png。没错。但 Bubble 目录只是实现了其他 BubbleX 目录。我该怎么做才能获取所有最后一个子目录的列表?

最佳答案

root 将是行走期间的当前目录。如果其中任何文件满足您的条件,请将 root 添加到列表(或其他容器)。

dirs_i_want = []
for root, dirs, files in os.walk(path):
    if any(fyle.endswith('png') for fyle in files:
        dirs_i_want.append(root)

如果您希望目录包含符合您条件的文件,请在条件语句中使用all

...
    if all(fyle.endswith('png') for fyle in files:
        ...

关于python - 使用 os.walk 在 python 中仅列出所有带有 png 的子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55420017/

相关文章:

jupyter-notebook - 在 Google Colab 中导入 .py 文件

image - 有效存储许多缩略图的方法

Python:LogLog 图与线性图相结合

python - KNN - 我如何加速?

r - 如何在具有 R 内核的 Jupyter 笔记本中查看数据帧的所有行?

python - 将 wav 文件传递​​到 IPython.display 时出错

python - 502 错误网关 : Registered endpoint failed to handle the request.:Python

python - "ImportError: cannot import name"全新安装 Anaconda

data-structures - 用于目录结构的数据结构?

powershell - 列出所有不包含通配符匹配文件的目录