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

manisha
  • 665
  • 3
  • 8
  • 15
  • possible duplicate of [Python: Iterate through folders, then subfolders and print filenames with path to text file](http://stackoverflow.com/questions/19932130/python-iterate-through-folders-then-subfolders-and-print-filenames-with-path-t) – Peter Gibson Apr 08 '14 at 06:37
  • No @Peter as mentioned I am not dealing with files but folders. Also, I don't know the depth at which the folder is located. – manisha Apr 08 '14 at 09:27

4 Answers4

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)
michaelmeyer
  • 7,985
  • 7
  • 30
  • 36
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

alphanumeric
  • 17,967
  • 64
  • 244
  • 392
0

You can use os.walk() method.

import os

folders = []

for path, dirs, files in os.walk(starting_path):
    folders.append(path)
    print path
lucaboni
  • 2,334
  • 2
  • 29
  • 41
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.

anon582847382
  • 19,907
  • 5
  • 54
  • 57