简体   繁体   English

如何在python中获取具有特定文件夹兄弟的特定文件夹

[英]How can I get a specific folder with a specific folders sibling in python

I would like to find the path to specific folders that have only specific folders brothers 我想找到只有特定文件夹兄弟的特定文件夹的路径

ex: I want to find all folders named : zeFolder with siblings folders brotherOne and brotherTwo 例如:我想找到所有名为的文件夹: zeFolder with siblings folders brotherOnebrotherTwo

|-dad1 | -dad1
|---brotherOne | --- brotherOne
|---brotherFour | --- brotherFour
|---zeFolder ( not match ) | --- zeFolder( 不匹配

|-dad2 | -dad2
|---brotherOne | --- brotherOne
|---brotherTwo | --- brotherTwo
|---zeFolder (♥♥♥Match♥♥♥) | --- zeFolder(♥♥♥Match♥♥♥)

[...] [...]

Below is my code, but with this solution I find all the folders. 下面是我的代码,但是通过这个解决方案,我找到了所有的文件夹。

import os
for root, dirs, files in os.walk("/"):
    #print (dirs)
    for name in dirs:
        if name == 'totolo':
                print ('finded')
                print(os.path.join(root, name))

I don't know how to use Conditional Statements to do that 我不知道如何使用条件语句来做到这一点

Thanks for you help. 谢谢你的帮助。

Basically it sounds like you want to find a specific set of subfolders so using sets is both natural and makes this a fairly easy thing to do. 基本上听起来你想要找到一组特定的子文件夹,所以使用sets是自然的,这使得这是一件相当容易的事情。 Their use also removes order dependencies when checking for equality. 在检查相等性时,它们的使用也会删除顺序依赖性。

import os

start_path = '/'
target = 'zeFolder'
siblings = ['brotherOne', 'brotherTwo']
sought = set([target] + siblings)

for root, dirs, files in os.walk(start_path):
    if sought == set(dirs):
        print('found')

What about using lists 怎么样使用列表

import os

folder = 'zeFolder'
brothers = ['brotherOne', 'brotherTwo']

for dirpath, dirnames, filenames in os.walk('/'):
    if folder in dirnames and all(brother in dirnames for brother in brothers):
        print 'matches on %s' % os.path.join(dirpath, 'zeFolder') 

or sets 或套装

import os

folder = 'zeFolder'
brothers = set(['brotherOne', 'brotherTwo', folder])

for dirpath, dirnames, filenames in os.walk('/'):
    if set(dirnames).issuperset(brothers) :
        print 'matches on %s' % os.path.join(dirpath, 'zeFolder') 

Both run at same speed for me. 两者都以相同的速度运行。

import os
import glob

filelist = glob.glob(r"dad1/*brotherOne")
for f in filelist:
    print(f)

filelist = glob.glob(r"dad1/*brotherTwo")
for f in filelist:
    print(f)

You could also try the glob technique. 你也可以试试glob技术。 And do whatever action you'd like to in the for loop. 并在for循环中执行您想要的任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM