【问题标题】:Traverse directories to a specific depth in Python [duplicate]在Python中将目录遍历到特定深度[重复]
【发布时间】:2018-02-19 04:32:10
【问题描述】:
例如,我想搜索和打印 c:// 下的目录,但只列出第 1 层和第 2 层,它们确实包含 SP30070156-1。
什么是使用 python 2 获得此功能的最有效方法,而无需通过整个子目录运行脚本(在我的情况下如此之多,需要很长时间)
典型的目录名称如下:
Rooty Hill SP30068539-1 3RD Split Unit AC Project
Oxford Falls SP30064418-1 Upgrade SES MSB
Queanbeyan SP30066062-1 AC
【问题讨论】:
标签:
python
list
directory
os.walk
【解决方案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
然后您可以使用 string='SP30070156-1' 和级别 1 然后级别 2 调用它。
但不确定它是否会超过 40 秒。
【解决方案2】:
这是我使用的代码,方法很快列出,如果过滤关键字则更快
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"