python搜索子目录 [英] python Search for subdirectories
问题描述
我想创建一个名称中包含"HICU-B"的所有子目录的列表.仅目录不包含文件(父目录中的某些文件也包含此文件).
I'd like to create a list of all sub-directories that contain "HICU-B" in their name. Only directories not files (some files in the parent directory contain this too).
我想知道是否有一种方法可以将glob
和os.walk()
组合在一起以实现此目的.或者,如果还有另一种解决方法.
I'm wondering if there is a way to combine glob
and os.walk()
together to accomplish this. Or if there is another way to go about it.
这是我到目前为止的代码:
This is the code I have so far:
这将获取包含我想要的文本的文件和目录.
This gets the files and directories that contain the text I would like.
dirstext=glob.glob('/data01/HICU-B*')
这将获取目录.
dirs=next(os.walk('/data01'))[1]
我不知道如何将它们组合在一起,以获得仅名称中带有"HICU-B"的目录,而不是文件.
I can't figure out how to combine them to get just the directories with "HICU-B" in the name and not the files.
有想法吗?
推荐答案
在HICU-B*
的末尾添加斜线'/'
:
dirstext = glob.glob('/data01/HICU-B*/')
这只会返回名称以HICU-B*
开头的目录,而文件将被排除.
This would return only directories with names starting with HICU-B*
while files will be excluded.
如果需要通过walk
在匹配的目录中返回其所有子目录和文件,则可以执行以下操作:
If you need to walk
through the matching directories to return all their subdirectories and files, you can do:
dirs = [list(i) for i in map(os.walk, dirstext)]
这篇关于python搜索子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!