首页 > 解决方案 > 用于目录搜索的 Python rglob 模式

问题描述

我尝试在 Windows10 上使用 Python3 脚本获取子目录的名称。因此,我编写了如下代码:

from pathlib2 import Path
p = "./path/to/target/dir"
[str(item) for item in Path(p).rglob(".")]
# obtained only subdirectories path names including target directory itself.

得到这个结果对我有好处,但我不知道为什么 rglob 参数的模式会返回这个结果。

有人可以解释一下吗?

谢谢。

标签: pythonpython-3.xpathlib

解决方案


posix 风格文件系统中的每个目录从一开始就具有两个文件:..,它指的是父目录, 和.,它指的是当前目录:

$ mkdir tmp; cd tmp
tmp$ ls -a
. ..
tmp$ cd .
tmp$  # <-- still in the same directory

- 除了/..,它指的是根本身,因为根没有父级。

Path来自 python 的对象在创建pathlib时只是一个围绕一个字符串的包装器,该字符串假定指向文件系统的某个位置。它只会在解决时指代有形的东西:

>>> Path('.')
PosixPath('.')  # just a fancy string
>>> Path('.').resolve()
PosixPath('/current/working/dir')  # an actual point in your filesystem

底线是

  • 从文件系统的角度来看,路径/current/working/dir和是完全等效的,并且/current/working/dir/.
  • apathlib.Path也将在解决后立即反映出来。

通过匹配对 的glob调用.,您发现所有指向初始目录下的当前目录的链接。结果glob在返回时得到解决,因此.不再出现在那里。

作为此行为的来源,请参阅PEP428 的这一部分(用作 的规范pathlib),其中简要提到了路径等效性。


推荐阅读