You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表推导式过滤目录异常:多级目录仅解析反斜杠

问题:多级目录路径过滤异常

用户尝试用glob获取多级目录路径,再通过列表推导式过滤出目录,但执行后过滤结果仅保留了点和反斜杠。相关代码及输出如下:

原代码

#To pull content from dirNames directory
dirNames = str(glob.glob('.\Output'+ globalData.__TWO_BACK_SLASH_SEPERATORS__ + globalData.__MANUAL_STRING_OUTPUT__ + globalData.__TWO_BACK_SLASH_SEPERATORS__ +'*'))
print ("Dir Names:: "+dirNames)

#Seperate the contents of dirNames into list dirNames[0], dirNames[1]....etc
dirNames = [dir for dir in dirNames if os.path.isdir( dir)]
print("\nPost Filetring Dir names are ::{}".format(dirNames))

执行输出

Output: Dir Names:: ['.\Output\ManualOutput\152_156_92_230_NLA_6_0_0_08112022',
'.\Output\ManualOutput\152_156_92_230_NLA_6_0_0_112022_1_REV01',
'.\Output\ManualOutput\152_156_92_230_NLA_6_0_0_21112022_1_REV01']

Post Filetring Dir names are ::['.', '', '', '', '', '',
'', '.', '', '', '', '', '', '', '.', '', '', '',
'', '', '']

错误原因

核心问题是把glob返回的路径列表转成了字符串,后续遍历的是字符串的每个字符,而非原列表中的完整路径。比如原列表是[路径1, 路径2],转成字符串后变成了"[路径1, 路径2]",遍历这个字符串时,每个字符(包括[、'、.、\等)都会被检查是否为目录,最终只有.和\符合条件,导致结果异常。

单级目录时看似正常只是巧合,本质逻辑完全错误。

修正方案

直接使用glob返回的列表,不要转成字符串,同时推荐用os.path.join拼接路径,避免手动处理分隔符的麻烦:

import glob
import os
import globalData

# 用os.path.join构建路径模式,自动适配系统分隔符
pattern = os.path.join('.', 'Output', globalData.__MANUAL_STRING_OUTPUT__, '*')

# glob返回的本身就是路径列表,无需转字符串
dir_list = glob.glob(pattern)
# 过滤出目录(保险起见,避免glob匹配到文件)
dir_list = [path for path in dir_list if os.path.isdir(path)]

print("Dir Names:: ", dir_list)
print("\nPost Filtering Dir names are ::", dir_list)

额外优化

如果需要递归获取所有子目录,可以启用glob的递归模式:

# 递归获取目标目录下所有子目录
pattern = os.path.join('.', 'Output', globalData.__MANUAL_STRING_OUTPUT__, '**')
dir_list = glob.glob(pattern, recursive=True)
dir_list = [path for path in dir_list if os.path.isdir(path)]

内容的提问来源于stack exchange,提问作者CaffeineAndCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 14:10:29