在python中,如何获得一个具有特定同级文件夹的特定文件夹

2024-06-16 11:12:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如: 我想找到所有名为:zeFolder的文件夹,其中有同级文件夹brotherOne和{}

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

|-dad2
|---BrotherRone
|---brotherTwo
|---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))

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

谢谢你的帮助。在


Tags: namein路径文件夹forosroot兄弟
3条回答

基本上,听起来你想找到一组特定的子文件夹,所以使用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')

使用列表怎么样

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

或套

^{pr2}$

对我来说,两人跑得一样快。在

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循环中做你想做的任何事。在

相关问题 更多 >