1

I am pretty new to python and I need to search for a folder that has a name like: vvl*cpp and is always present inside a directory named test. But the problem is the depth of the test directory is not known.

I tried:

dir_name=glob.glob('./[a-z,_]*/test/vvl*cpp')
    file_dict={}
    for i in dir_name:
        name=re.compile(r"\.\/[a-z,_]*\/test\/vvl_")
        file_name=name.sub("",i)
        file_dict[file_name]=i

for key in sorted(file_dict.iterkeys()):
    print "%s: %s" % (key, file_dict[key])

But it only searches in the sub directory but as i mentioned i have no idea about the depth of test directory. It may be 1 it may be 10. Please suggest me some way out. I am using python2.6

2

4 Answers 4

1

This is straightforward if you consider that you need two components:

  1. A function that iterate over a directory recursively.
  2. A function that check if a directory is match.

For the first one:

def walk_tree(path):
    for root, dirs, files in os.walk(path):
        for dir in dirs:
            yield root, dir

For the second one:

def is_a_match(dirparent, dirname):
    return os.path.basename(dirparent) == "test" and \
    dirname.startswith("vvl") and dirname.endswith("cpp")

And now put it all together:

def iter_targets(path):
    for dirparent, dirname in walk_tree(path):
        if is_a_match(dirparent, dirname):
            yield os.path.join(dirparent, dirname)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @doukremt it very well served the purpose
I like it! Very neat!
0

I like a logic in this code:

for myDir, myDirs, myFilenames in os.walk(myPath):
    print type(myDir), myDir
    print type(myDirs), myDirs
    print type(myFilenames), myFilenames

You can nail the rest with os.path methods such as: os.path.abspath(), os.path.dirname() and etc

Comments

0

You can use os.walk() method.

import os

folders = []

for path, dirs, files in os.walk(starting_path):
    folders.append(path)
    print path

Comments

0

I would do this- crawl the tree with os.walk, check against your condition with a lambda and accumulate the matches with a list comprehension:

cond = lambda x, y: os.path.basename(x) == 'test' and 
                    y.startswith('vvl') and y.endswith('cpp')
matches = (os.path.join(r, d) for r, d, f in os.walk(tree) if cond(r, d))

Hopefully that is what you meant, it is kind of unclear.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.