<p>我真的很喜欢<a href="https://stackoverflow.com/a/3215392/901641">adamk's answer</a>,建议您使用来自同名模块的<code>glob()</code>。这允许您使用与<code>*</code>s匹配的模式</p>
<p>但正如其他人在评论中指出的,<code>glob()</code>可能会被不一致的斜杠方向绊倒。为此,我建议您使用<code>join()</code>模块中的<code>expanduser()</code>和<code>os.path</code>函数,也可以使用<code>os</code>模块中的<code>getcwd()</code>函数。</p>
<p>例如:</p>
<pre><code>from glob import glob
# Return everything under C:\Users\admin that contains a folder called wlp.
glob('C:\Users\admin\*\wlp')
</code></pre>
<p>上面的情况很糟糕-路径已经被硬编码,并且只能在驱动器名和被硬编码到路径中的<code>\</code>之间的窗口上工作。</p>
<pre><code>from glob import glob
from os.path import join
# Return everything under Users, admin, that contains a folder called wlp.
glob(join('Users', 'admin', '*', 'wlp'))
</code></pre>
<p>上面的方法工作得更好,但是它依赖于文件夹名<code>Users</code>,这个文件夹名通常在Windows上找到,而在其他OSs上却很少找到。它还依赖于具有特定名称<code>admin</code>的用户。</p>
<pre><code>from glob import glob
from os.path import expanduser, join
# Return everything under the user directory that contains a folder called wlp.
glob(join(expanduser('~'), '*', 'wlp'))
</code></pre>
<p>这在所有平台上都非常有效。</p>
<p>另一个很好的例子,它可以完美地跨平台工作,并且可以做一些不同的事情:</p>
<pre><code>from glob import glob
from os import getcwd
from os.path import join
# Return everything under the current directory that contains a folder called wlp.
glob(join(getcwd(), '*', 'wlp'))
</code></pre>
<p>希望这些示例能帮助您了解一些在标准Python库模块中可以找到的函数的强大功能。</p>