我认为最简单和最稳定的方法是复制os.walk
straight out of the source的功能并插入您自己的深度控制参数。
import os
import os.path as path
def walk(top, topdown=True, onerror=None, followlinks=False, maxdepth=None):
islink, join, isdir = path.islink, path.join, path.isdir
try:
names = os.listdir(top)
except OSError, err:
if onerror is not None:
onerror(err)
return
dirs, nondirs = [], []
for name in names:
if isdir(join(top, name)):
dirs.append(name)
else:
nondirs.append(name)
if topdown:
yield top, dirs, nondirs
if maxdepth is None or maxdepth > 1:
for name in dirs:
new_path = join(top, name)
if followlinks or not islink(new_path):
for x in walk(new_path, topdown, onerror, followlinks, None if maxdepth is None else maxdepth-1):
yield x
if not topdown:
yield top, dirs, nondirs
for root, dirnames, filenames in walk(args.directory, maxdepth=2):
#...
如果你没有兴趣在所有这些可选参数,你几乎可以大幅削减下来的功能:
import os
def walk(top, maxdepth):
dirs, nondirs = [], []
for name in os.listdir(top):
(dirs if os.path.isdir(os.path.join(top, name)) else nondirs).append(name)
yield top, dirs, nondirs
if maxdepth > 1:
for name in dirs:
for x in walk(os.path.join(top, name), maxdepth-1):
yield x
for x in walk(".", 2):
print(x)
这是一个小问题,一个相当长的一段代码..如果可能的话,我更喜欢更紧凑的解决方案。我认为你的意思是......在步行(......)中:'在第二行而不是'os.walk'中,不是吗? –
有趣的是,我只是撰写了一个较短的版本:-),而且你倒数第二行的错误“os.”是正确的。固定。 – Kevin
这个短版看起来很酷。我修改它不返回目录(因为我只需要文件),并比较'if maxdepth!= 0',以便0表示仅表示当前目录,我可以使用负值传递整个目录结构。 –