2017-09-11 128 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多岁快,但是。