简体   繁体   中英

How to find directory in python recursively

Say, I have the directories structure like:

foo1/
├── bar2/
│   └── ...
└── bar4/
    └── ...

I want to write a function that will find the directory I am looking for and it's parent directory, like

def directory_find(atom):
    # ....

directory_find(bar4)

so this would return me foo3/bar4 as a result, the parent directory may not be known initially, so that's why I am thinking of the recursive search.

It seems the os module does not do what I want as it works only for files this way.

That's what os.walk() does for you; it'll traverse a nested directory structure, and tell you at each step what the filenames and directories are.

Your search can be implemented as:

def directory_find(atom, root='.'):
    for path, dirs, files in os.walk(root):
        if atom in dirs:
            return os.path.join(path, atom)

Demo:

>>> import os
>>> os.makedirs("foo1/bar2", exist_ok=True)
>>> os.makedirs("foo1/bar4", exist_ok=True)
>>> directory_find('bar2')
'./foo1/bar2'
>>> directory_find('bar4')
'./foo1/bar4'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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