python - 用于目录搜索的 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 参数的模式会返回这个结果。
有人可以解释一下吗?
谢谢。
解决方案
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/.
- a
pathlib.Path
也将在解决后立即反映出来。
通过匹配对 的glob
调用.
,您发现所有指向初始目录下的当前目录的链接。结果glob
在返回时得到解决,因此.
不再出现在那里。
作为此行为的来源,请参阅PEP428 的这一部分(用作 的规范pathlib
),其中简要提到了路径等效性。
推荐阅读
- struct - 将值推送到 Julia 中的结构元素时出现问题
- c# - SendMessage 到 Notepad++ 打开一个文件
- android - 将数据复制到新表时,NOT NULL 约束失败
- amazon-ec2 - AWS API Gateway 在使用私有 IP 地址调用后端 API 时失败
- python - 在 QMenu 的指定位置插入新项目
- php - 我使用函数 dirToArray 收到错误“TypeError(“无法将类作为函数调用”)”
- jquery - jQuery datepicker 日期数组禁用日期不正确
- c# - 如何扩展 CollectionView 的过滤器?
- php - 使用 PHP HMAC SHA1 和 Base64 创建身份验证字符串时遇到问题
- mapbox - 优化和跟踪 Mapbox 地图视图