Python扫描目录并消除重复目录



我必须用有限的最深值递归地扫描目录。我正在使用操作系统模块实现这一点。下面是代码

scan_dir = "/a/b/c"
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(os.path.join(top,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(scan_dir, 2):
_, dir_list, nondirs_list = x
dirs_final = dirs_final + dir_list
nondirs_final = nondirs_final + nondirs_list

因为我们的内存不足,如果我们扫描/a/b/c,因为它有很多文件(下面的代码扫描功能,我们正在使用仅供参考)来修复内存问题,我认为扫描较小的子目录4级最深。

from pathlib import Path
def scan(path):
for Entry in Path(path).iterdir():
if Entry.is_dir() and not Entry.is_symlink():
yield Entry
for SubEntry in scan(Entry):
yield SubEntry
else:
yield Entry
所有子目录都存在于dirs_final中,但它包含以下路径
example: /a/b/c/d
/a/b/c/d/e/f/g
/a/b/c/d/e/f

在上述情况下,我们扫描"/a/b/c/d/e/f/g"3次,一次在/a/b/c/d期间,另一次

/a/b/c/d/e/f和其他/a/b/c/d/e/f/g

如何避免在dirs_final列表中重复,以便我只扫描一次

可以使用set()作为输出:

def walk( root, dirs, files, max_depth=4, depth=0 ):
try:
for node in os.listdir( root ):
full_path = os.path.join( root, node )
# skip symlinks
if os.path.islink( full_path ):
continue
if os.path.isfile( full_path ): 
files.add( node )
else:
# print( full_path )
dirs.add( node )    
if depth < max_depth:
walk( full_path, dirs, files, max_depth, depth=depth+1 )
except Exception as errors:
pass # print( errors )

用法:

dirs    = set()
files   = set()
walk( '/usr/bin', dirs, files )

最新更新