擅长:python、mysql、java
<p>为什么不<a href="https://docs.python.org/3/library/os.html?highlight=walk#os.walk" rel="nofollow"> os.walk</a></p>
<blockquote>
<p>When topdown is True, the caller can modify the dirnames list in-place
(perhaps using del or slice assignment), and walk() will only recurse
into the subdirectories whose names remain in dirnames; this can be
used to prune the search, impose a specific order of visiting, or even
to inform walk() about directories the caller creates or renames
before it resumes walk() again. Modifying dirnames when topdown is
False is ineffective, because in bottom-up mode the directories in
dirnames are generated before dirpath itself is generated.</p>
</blockquote>
<p>例如,您可以构建只生成非限制目录的生成器(惰性列表)</p>
<pre><code>for (dirpath, dirnames, filenames) in os.walk("top_path"):
if restricted(dirpath):
del dirnames
continue
yield (dirpath,tuple(filenames))
</code></pre>