这个路径是什么意思/***.jpg?

2024-04-27 14:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在IBM应用人工智能课程中遇到了这个问题:

path_for_license_plates = os.getcwd() + "/license-plates/**/*.jpg"

在上述路径中**/*.jpg是什么意思


Tags: path路径foroslicenseibm人工智能课程
3条回答

它显然是“递归”模式下的全局模式,如 “**”表示

给定目录树

license-plates/
├── a
│   ├── b
│   │   └── x.jpg
│   └── x.jpg
└── x.jpg

功能 ^{} 工作如下:

>>> import glob
>>> glob.glob('license-plates/**/*.jpg', recursive=True)
['license-plates/x.jpg', 'license-plates/a/x.jpg', 'license-plates/a/b/x.jpg']

https://docs.python.org/3/library/glob.html

glob.glob(pathname, *, recursive=False)

If recursive is true, the pattern “**” will match any files and zero or more directories, subdirectories and symbolic links to directories. If the pattern is followed by an os.sep or os.altsep then files will not match.

path_for_license_plates字面上是一个字符串。 就这样

它可以用来告诉我所有的jpg文件递归地在“license plates”下的所有目录中查找。 一个更好的问题是“以后如何在程序中使用它?”

很可能(因为他们使用了操作系统模块),这是一个较旧的程序。正如其他人所示,这倾向于使用glob模块。但是如果你要改变这个程序,你可以使它现代化

使用现代python(3.6+)时,您可以询问相同的信息:

from pathlib import Path
path_for_license_plates = Path('license-plates').glob("**/*.jpg")
for license_plate_file_location in path_for_license_plates:
    print(license_plate_file_location)

这将假定许可证位于当前工作目录中,并为您提供一个生成器,该生成器将生成更短的代码,这也适用于主要的文件系统。(windows/linux/mac)

相关问题 更多 >