我想在Python中获取某个目录的所有孙子.出于性能原因,我不想继续在循环中调用OS函数(它是一个网络文件系统).这就是我现在所拥有的.有更简单的方法吗?
dirTree = os.walk(root)
children = [os.path.join(root, x) for x in dirTree.next()[1]]
grandChildren = []
for root, dirs, files in dirTree:
if root in children:
for dir in dirs:
grandChildren.append(os.path.join(root, dir))
Run Code Online (Sandbox Code Playgroud)
编辑:我不清楚我对os.walk的调用是否是懒惰的.我的意图是整个树应该在我的电话后记忆中,但我不确定.
小智 5
如果我的问题是对的.
你可以使用glob来获取文件或目录,方法是给出通配符.例如,你可以在列表中的"/ home /"中获取所有目录.
glob.glob('/home/*/*/')
Run Code Online (Sandbox Code Playgroud)
或者你也可以知道所有文件
glob.glob('/home/*/*')
Run Code Online (Sandbox Code Playgroud)