Python3创建文件夹中图像的列表

bvuwiixz  于 2023-05-02  发布在  Python
关注(0)|答案(7)|浏览(126)

我在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图像在该路径中。
我的最佳方法是什么?

ohtdti5x

ohtdti5x1#

你可以使用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

后面跟着操作系统。sep,只有目录和子目录匹配。
假设你的abs路径是myfolder

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

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

bvk5enib

bvk5enib2#

Python 3中的pathlib模块使这变得简单:

from pathlib import Path
images = Path("/var/www/html/myfolder/images").glob("*.jpg")

想要所有的jpg图像递归地在那个目录下吗?使用.glob("*/**.jpg")
请注意,这是在创建Path对象的数组。如果你想要字符串,只需转换它们:

image_strings = [str(p) for p in images]
sulc1iza

sulc1iza3#

如果您指定了路径,则有多种方法可以查找该目录中的所有文件。一旦你有了这个列表,你就可以简单地遍历它并创建图像。
参见:How do I list all files of a directory?
一个很好的方法是使用操作系统。listdir*:

import os

# specify the img directory path
path = "path/to/img/folder/"

# list files in img directory
files = os.listdir(path)

for file in files:
    # make sure file is an image
    if file.endswith(('.jpg', '.png', 'jpeg')):
        img_path = path + file

        # load file as image...
kgsdhlau

kgsdhlau4#

只扫描顶层

import os
path = "path/to/img/folder/"
jpgs = [os.path.join(path, file)
        for file in os.listdir(path)
        if file.endswith('.jpg')]

若要递归扫描,请将最后一行替换为

jpgs = [os.path.join(root, file)
        for root, dirs, files in os.walk(path)
        for file in files
        if file.endswith('.jpg')]
ddarikpa

ddarikpa5#

import os

images=[]

def getFiles(path):
    for file in os.listdir(path):
        if file.endswith(".jpg"):
            images.append(os.path.join(path, file))

图像列表:

filesPath = "/var/www/html/myfolder/images"

getFiles(filesPath)
print(images)
dphi5xsq

dphi5xsq6#

  • 现代的方法是使用pathlib,它将路径视为对象,而不是字符串。作为一个对象,所有路径都有方法来访问路径的各个组件(例如:例如.suffix.stem)。
  • pathlib还具有:
  • .glob内置
  • .open方法(e.g. Path.open(mode='r')
  • Python 3's pathlib Module: Taming the File System

编码:

from pathlib import Path

jpg_files = Path('/some_path').glob('*.jpg')

for file in jpg_files:
    with file.open(mode='r') as f:
        ...
        do some stuff
wvt8vs2t

wvt8vs2t7#

imutils包中已经存在解决方案

from imutils import paths
path_img = "my_folder"
images = list(paths.list_images(path_img))

相关问题