擅长:python、mysql、java
<p><code>Dir</code>的Ruby实现在C语言中(根据<a href="http://www.ruby-doc.org/core-1.9.3/Dir.html">this documentation</a>,文件<code>dir.c</code>)。但是,Python的等价物实现了<a href="http://hg.python.org/cpython/file/abe8a2908f08/Lib/os.py#l209">in Python</a>。在</p>
<p>Python的性能不如C并不奇怪,但Python中使用的方法提供了更多的灵活性——例如,在遍历目录层次结构时,可以跳过名为<code>'.svn'</code>、<code>'.git'</code>、<code>'.hg'</code>的子树。在</p>
<p>大多数时候,Python实现已经足够快了。在</p>
<p><strong>更新:</strong>跳过文件/子目录根本不会影响遍历<em>速率</em>,但处理目录树所需的总时间肯定会减少,因为您可以避免遍历主树中潜在的大型子树。节省的时间当然与你跳过多少成正比。在您的例子中,它看起来像是图像的文件夹,您不太可能节省很多时间(除非图像处于修订控制之下,跳过修订控制系统拥有的子树可能会有一些影响)。在</p>
<p><strong>其他更新:</strong>跳过文件夹是通过更改<code>dirs</code>值来完成的:</p>
<pre><code>for root, dirs, files in os.walk(path):
for skip in ('.hg', '.git', '.svn', '.bzr'):
if skip in dirs:
dirs.remove(skip)
# Now process other stuff at this level, i.e.
# in directory "root". The skipped folders
# won't be recursed into.
</code></pre>