python - 在 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'
有没有更好的方法来做到这一点?
解决方案
我会使用rglob
from 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)
推荐阅读
- ios - 当我向左或向右滑动 Settings Bundle 中的 Slider 时,更改 ViewController 中 UILabel 的背景
- c# - c# Office Interop 循环遍历大型文档中的每个单词时速度很慢
- node.js - NPM 安装时构建失败 - 打字
- excel - 如何使用 SUMIF 结合 VLOOKUP
- sql - 即使不存在也选择记录
- javascript - Angular Universal:“在工作区中找不到项目。”
- python - 将熊猫系列作为新列添加到特定的 Dataframe 行
- scala - 链表连接的复杂性
- java - 对 SonarQube 7.x 的 Java 运行时引擎支持
- javascript - Unicode 在我的 php 中不起作用