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.
得到这个结果对我来说很好,但我不知道为什么 rglob 参数的模式返回这个结果。
有人可以解释一下吗?
谢谢。
posix 风格文件系统中的每个目录从一开始就有两个文件:..,指的是父目录, 和.,指的是当前目录:
$ mkdir tmp; cd tmp
tmp$ ls -a
. ..
tmp$ cd .
tmp$  # <-- still in the same directory
- 值得注意的例外是/..,它指的是根本身,因为根没有父级。
PathPython 中的对象在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/.pathlib.Path一旦解决,a也会反映这一点。通过匹配glob对 的调用.,您可以找到指向初始目录下的当前目录的所有链接。结果glob在返回时得到解决,因此.不再出现在其中。
作为此行为的来源,请参阅PEP428 的这一部分(用作 的规范pathlib),其中简要提到了路径等效性。
| 归档时间: | 
 | 
| 查看次数: | 30540 次 | 
| 最近记录: |