2017-09-11 62 views
0

我想搜索並打印c://下的目錄,但僅列出包含SP30070156-1的第1和第2級別的目錄。將目錄遍歷到Python中的特定深度

什麼是最有效的方式來得到這個使用python 2而不運行腳本,雖然整個子目錄(在我的情況那麼多,將需要很長的時間)

典型的目錄名如下:

Rooty Hill SP30068539-1 3RD Split Unit AC Project 
Oxford Falls SP30064418-1 Upgrade SES MSB 
Queanbeyan SP30066062-1 AC 
+0

我是蟒蛇2後更快 – Ossama

回答

0

這裏是我使用的代碼,該方法是快速列表中,如果過濾關鍵字,然後它

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" 
1

你可以嘗試創建一個基於os.walk()的函數。像這樣的東西應該讓你開始:

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 

然後,你可以用字符串=「SP30070156-1」和1的水平,那麼2級

不知道叫它它是否會比40多歲快,但是。