我需要一些提示并帮助解决我的问题。 我想在 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/