Jupyter Notebook运行Python3.8代码触发WinError 267目录名无效报错
问题根因
- 触发
[WinError 267] 目录名无效的核心逻辑和代码写法直接相关:- 路径拼接不规范:全程用f-string手写路径,混用Windows原生的
\分隔符和代码里的/分隔符,且异常报错中的无效路径末尾额外附带了斜杠,让系统把本该指向.JPG图像文件的路径,解析为“该JPG文件下的子目录”,而JPG是普通文件不是目录,自然识别为无效路径 - 路径字符串存在潜在转义风险:根路径
directory_root = "E:\PlantVillage"未使用原始字符串定义,当后续路径段中存在\n、\t等合法转义序列时,会导致路径内容被意外篡改,进一步引发拼接错位 - 列表遍历删除逻辑存在缺陷:代码中边遍历文件夹列表、边从原列表中移除
.DS_Store文件的写法,会导致列表索引错位,漏遍历、错遍历部分文件,间接引发路径拼接异常
- 路径拼接不规范:全程用f-string手写路径,混用Windows原生的
修复方案
- 统一使用Python内置的
os.path模块完成所有路径操作,彻底替代手写f-string拼接路径的逻辑,从根源上适配Windows的路径规则,避免分隔符混用、末尾多斜杠的问题:- 导入依赖时用原始字符串定义根路径,规避转义风险:
import os from os import listdir # 前缀r代表原始字符串,会完整保留路径中的反斜杠,不做转义解析 directory_root = r"E:\PlantVillage"- 把所有手写拼接路径的位置,全部替换为
os.path.join方法自动适配分隔符,示例替换对照:- 原遍历作物文件夹列表的写法:
listdir(f"{directory_root}/{plant_folder}")替换为listdir(os.path.join(directory_root, plant_folder)) - 原遍历病害子文件夹图像列表的写法:
listdir(f"{directory_root}/{plant_folder}/{plant_disease_folder}/")替换为listdir(os.path.join(directory_root, plant_folder, plant_disease_folder)) - 原生成单张图像路径的写法:
image_directory = f"{directory_root}/{plant_folder}/{plant_disease_folder}/{image}"替换为image_directory = os.path.join(directory_root, plant_folder, plant_disease_folder, image)
- 原遍历作物文件夹列表的写法:
- 替换边遍历边删除
.DS_Store的逻辑,直接通过列表推导式在生成列表时就过滤掉无关文件,避免索引错位:
# 替代原循环删除的写法,生成列表时直接过滤 root_dir = [f for f in listdir(directory_root) if f != ".DS_Store"] plant_disease_folder_list = [ f for f in listdir(os.path.join(directory_root, plant_folder)) if f != ".DS_Store" ] - 增加路径合法性校验,在调用图像加载方法前提前拦截无效路径:
# 统一用小写判断后缀,同时校验路径是真实存在的文件 if image_directory.lower().endswith((".jpg", ".jpeg")) and os.path.isfile(image_directory): image_list.append(convert_image_to_array(image_directory)) label_list.append(plant_disease_folder)
注意:Windows系统对路径末尾的斜杠有特殊解析规则,只要路径指向普通文件,末尾追加斜杠就会被判定为寻找该文件对应的子目录,直接触发目录无效的报错,所有涉及文件定位的代码都不要在文件路径末尾额外拼接斜杠。
内容的提问来源于stack exchange,提问作者Baazigar
相关产品推荐
相关产品推荐

