用于目录搜索的 Python rglob 模式

tse*_*ine 9 python python-3.x pathlib

我尝试在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.
Run Code Online (Sandbox Code Playgroud)

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

有人可以解释一下吗?

谢谢。

Arn*_*rne 5

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

$ mkdir tmp; cd tmp
tmp$ ls -a
. ..
tmp$ cd .
tmp$  # <-- still in the same directory
Run Code Online (Sandbox Code Playgroud)

- 值得注意的例外是/..,它指的是根本身,因为根没有父级。

PathPython 中的对象在pathlib创建时只是一个字符串的包装器,该字符串被假定指向文件系统中的某个位置。当它被解决时,它只会指有形的东西:

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

底线是

  • 从文件系统的角度来看,路径/current/working/dir和是完全等效的,并且/current/working/dir/.
  • pathlib.Path一旦解决,a也会反映这一点。

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

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