【问题标题】:List only all subdir´s with png´s inside in python with os.walk使用os.walk在python中仅列出所有带有png的子目录
【发布时间】:2019-03-29 14:49:21
【问题描述】:

我需要一些提示和帮助来解决我的问题。 我想在 jupyter 笔记本中的目录上创建一个下拉菜单。在这个目录里面有 dir´s 和 png´s,以及一些 dir´s 和 subdir´s 和 png´s。现在我想得到一个里面有png的所有目录的列表。但不是里面有目录的目录。 ATM 我得到了每个目录,但那是错误的,因为我只能在里面使用带有 png 的目录。那是我的自动取款机:

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')

例如: 我有目录“学习集”,想要一个下拉列表。但是下拉菜单向我显示了 dir´s Bubble、Bubble1、Bubble2 等。dir´s BubbleX 里面有 png。那是正确的。但是 Bubble 目录只是实现了其他 BubbleX 目录。我该怎么做才能获得所有最后一个子目录的列表?

【问题讨论】:

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


【解决方案1】:

root 将是 walk 期间的当前目录。如果其中任何文件符合您的条件,请将 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:
        ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 2011-11-09
    • 2012-02-12
    • 1970-01-01
    • 2011-11-09
    • 2017-08-10
    • 1970-01-01
    相关资源
    最近更新 更多