首页 > 解决方案 > Python3在文件夹中创建图像列表

问题描述

我在 Python3 中有一组像这样的图像......

images = [
    "/var/www/html/myfolder/images/1.jpg",
    "/var/www/html/myfolder/images/441.jpg",
    "/var/www/html/myfolder/images/15.jpg",
    "/var/www/html/myfolder/images/78.jpg",
]

我不想像这样指定图像,而是想传递一个绝对路径并让 python 从该路径中的 .jpg 图像中创建图像列表。

我最好的方法是什么?

标签: pythonpython-3.x

解决方案


您可以使用 glob。

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

返回与路径名匹配的可能为空的路径名列表,该路径名必须是包含路径规范的字符串。路径名可以是绝对的(如 /usr/src/Python-1.5/Makefile)或相对的(如 ../../Tools/ / .gif),并且可以包含 shell 样式的通配符。结果中包含损坏的符号链接(如在 shell 中)。

If recursive is true, the pattern “**” will match any files and zero or more directories and subdirectories. If the pattern is

后跟一个 os.sep,只有目录和子目录匹配。

假设你的 abs 路径是myfolder

import glob
images = glob.glob('images/*.jpg')

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


推荐阅读