我需要递归处理目录树中的所有文件,但是深度有限。
例如,这意味着要在当前目录和前两个子目录级别中查找文件,但不能再查找其他文件。在这种情况下,我必须处理./subdir1/subdir2/file
,但不能处理./subdir1/subdir2/subdir3/file
。
我将如何在Python 3中做到最好?
目前,我使用os.walk
这样的循环来处理所有文件直至无限深度:
for root, dirnames, filenames in os.walk(args.directory):
for filename in filenames:
path = os.path.join(root, filename)
# do something with that file...
我可以想到一种计数目录分隔符(/
)的方法,root
以确定当前文件的层次级别,break
如果该级别超过所需的最大值,则确定循环。
当存在大量要忽略的子目录时,我认为这种方法可能不安全并且效率很低。这里的最佳方法是什么?
我认为最简单,最稳定的方法是直接复制os.walk
源代码的功能并插入自己的深度控制参数。
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句