代码之家  ›  专栏  ›  技术社区  ›  jmercier

如何在python中获取具有特定文件夹同级的特定文件夹

  •  1
  • jmercier  · 技术社区  · 10 年前

    我想找到只有特定文件夹兄弟的特定文件夹的路径

    前任: 我要查找名为的所有文件夹: zeFolder 具有同级文件夹 brotherOne brotherTwo

    |-数据1
    |---姐夫一号
    |---姐夫四
    |---ze文件夹( 不匹配 )

    |-数据2
    |---姐夫一号
    |---姐夫二
    |---zeFolder(匹配)

    [...]

    以下是我的代码,但使用此解决方案,我可以找到所有文件夹。

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

    我不知道如何使用条件语句来实现这一点

    谢谢你的帮助。

    3 回复  |  直到 10 年前
        1
  •  2
  •   martineau    10 年前

    基本上,您似乎想找到一组特定的子文件夹 sets 这是很自然的,这使得这是一件相当容易的事情。在检查相等性时,它们的使用也消除了顺序依赖性。

    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')
    
        2
  •  1
  •   Paul Rooney    10 年前

    如何使用列表

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

    或套

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

    对我来说,两个人的速度都一样。

        3
  •  0
  •   Death_Dealer    10 年前
    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)
    

    你也可以试试地球仪技术。在for循环中执行任何您想执行的操作。