擅长:python、mysql、java
<p>首先,<a href="http://docs.python.org/library/os.html#os.walk" rel="noreferrer">^{<cd1>}</a>没有指定目录返回的顺序,因此如果我是您,我就不会依赖字母顺序。</p>
<p>话虽如此,您可以通过将<a href="http://docs.python.org/library/os.html#os.walk" rel="noreferrer">^{<cd2>}</a>设置为其默认值(<code>True</code>),然后将<code>dirs</code>排序到位来选择遍历子目录的顺序:</p>
<pre><code>import os
top='/home/aix'
for root, dirs, files in os.walk(top, topdown=True):
print root
dirs.sort(reverse=True)
</code></pre>
<p>这将使<code>os.walk()</code>按名称的相反字典顺序遍历子目录。</p>
<p><a href="http://docs.python.org/library/os.html#os.walk" rel="noreferrer">documentation</a>解释了这是如何工作的:</p>
<blockquote>
<p>When <code>topdown</code> is <code>True</code>, the caller can modify the dirnames list in-place (perhaps using <code>del</code> or slice assignment), and <code>walk()</code> will only recurse into the subdirectories whose names remain in <code>dirnames</code>; this can be used to prune the search, impose a specific order of visiting, or even to inform <code>walk()</code> about directories the caller creates or renames before it resumes <code>walk()</code> again.</p>
</blockquote>