首页 > 解决方案 > 在 os.path.join() 函数中包含通配符以创建文件路径

问题描述

我正在尝试打开特定文件夹中的图像文件。不知道怎么通过代码来解释文件夹结构,所以分层次来说明文件夹结构如下:

level 1: data 
level 2: data\channel1                        data\channel2
level 3: data\channel1\morning                data\channel2\morning
             \channel1\evening                data\channel2\evening

level 4: data\channel1\morning\images.png     data\channel2\morning\images.png
         data\channel1\evening\images.png     data\channel2\evening\images.png

#where: 'images.png' are the image files

这是一个简化版本,但实际上在 3 级类别下有很多文件夹。例如早上、晚上、下午、午夜等。我想提取图像而不考虑这第 3 级

from PIL import Image
import os
import pandas as pd:

root = os.getcwd()
img_file_loc = Path('data')
channels = ['channel1', 'channel2']
file_name = 'star.png'

temp = []
for channel in channels:
    img_file_path = os.path.join(root, img_file_loc, channel, '\\*\\', file_name)
    x = Image.open(img_file_path)
    temp.append(x)

我尝试使用通配符,但它给了我如下错误:

OSError: [Errno 22] Invalid argument: ...'\\*\\star.png'

有没有更好的方法来做到这一点?

标签: pythonos.path

解决方案


我会使用rglobfrom pathlib

from pathlib import Path

img_file_loc = Path('path/to/data')
channels = ['channel1', 'channel2']
file_name = 'star.png'

for channel in channels:
    img_files = img_file_loc.rglob(file_name)
    for img_file in img_files:
        x = Image.open(img_file_path)
        temp.append(x)

推荐阅读