0

I would like to search and print directories under c:// for example, but only list 1st and 2nd levels down, that do contain SP30070156-1.

what is the most efficient way to get this using python 2 without the script running though the entire sub-directories (so many in my case it would take a very long time)

typical directory names are as follow:

Rooty Hill SP30068539-1 3RD Split Unit AC Project
Oxford Falls SP30064418-1 Upgrade SES MSB
Queanbeyan SP30066062-1 AC
Ossama
  • 2,401
  • 7
  • 46
  • 83

2 Answers2

1

You can try to create a function based on os.walk(). Something like this should get you started:

import os

def walker(base_dir, level=1, string=None):
    results = []
    for root, dirs, files in os.walk(base_dir):
        _root = root.replace(base_dir + '\\', '') #you may need to remove the "+ '\\'"
    if _root.count('\\') < level:
        if string is None:
            results.append(dirs)
        else:
            if string in dirs:
               results.append(dirs)
    return results

Then you can just call it with string='SP30070156-1' and level 1 then level 2.

Not sure if it's going to be faster than 40s, though.

AMC
  • 143
  • 1
  • 8
0

here is the code i used, the method is quick to list, if filtered for keyword then it is even quicker

import os


MAX_DEPTH = 1
#folders = ['U:\I-Project Works\PPM 20003171\PPM 11-12 NSW', 'U:\I-Project Works\PPM 20003171\PPM 11-12 QLD']
folders = ['U:\I-Project Works\PPM 20003171\PPM 11-12 NSW']
try:
    for stuff in folders:
        for root, dirs, files in os.walk(stuff, topdown=True):
            for dir in dirs:
                if "SP30070156-1" in dir:
                    sp_path = root + "\\"+ dir
                    print(sp_path)

                    raise Found
            if root.count(os.sep) - stuff.count(os.sep) == MAX_DEPTH - 1:
                del dirs[:]

except:
    print "found"
Ossama
  • 2,401
  • 7
  • 46
  • 83