【问题标题】:How can I get a specific folder with a specific folders sibling in python如何在python中获取具有特定文件夹兄弟的特定文件夹
【发布时间】:2015-03-02 22:11:23
【问题描述】:

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

例如: 我想找到所有名为:zeFolder 的文件夹以及兄弟文件夹 brotherOnebrotherTwo

|-dad1
|---brotherOne
|---brotherFour
|---zeFolder(不匹配

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

[...]

下面是我的代码,但是通过这个解决方案我可以找到所有文件夹。

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

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

感谢您的帮助。

【问题讨论】:

  • 您是否希望 brotherOnebrotherTwo 成为唯一的兄弟姐妹,或者是否还有其他兄弟姐妹,只要这两个兄弟姐妹在,它就会匹配?

标签: python os.walk


【解决方案1】:

基本上听起来您想找到一组特定的子文件夹,因此使用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】:

    如何使用列表

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

    对我来说,两者都以相同的速度运行。

    【讨论】:

    • 嗨,谢谢你的awser,我必须使用拉丁字符,当我打印像“é à”之类的文件夹时,我有一个错误,所以我使用:.encode('utf-8' )但现在我的字符串(字节)开头有一个 b' 我该如何删除它?并保持 utf-8 ty
    • 如果有人还没有回复,我明天会尽力回复您。不知道这对stackoverflow.com/questions/28246004/…有没有帮助?
    • 尝试解码而不是编码。 stackoverflow.com/questions/5974585/…
    • 当我尝试解码时,回溯:'str object has no attrbute decode'
    • 我用这个代码 myData = myData[2:-1] 的 sn-p 作弊,我知道它很脏;如果您有时间,请为您的遮阳篷提供服务
    【解决方案3】:
    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)
    

    您也可以尝试 glob 技术。并在 for 循环中执行您想要执行的任何操作。

    【讨论】:

      猜你喜欢
      • 2018-03-06
      • 2016-03-05
      • 2020-10-31
      • 1970-01-01
      • 2022-08-05
      • 1970-01-01
      • 2022-01-22
      • 2022-07-18
      • 1970-01-01
      相关资源
      最近更新 更多