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

如何更精简地获取嵌套目录下所有.xml后缀文件的路径

你现有代码的三层循环属于冗余逻辑,且存在兼容性隐患:os.walk返回的root已经是当前遍历到的目录的完整路径,不需要额外遍历dirs拼接路径,当前代码能正常输出仅因为你的目录结构只有两级,一旦出现更深的子目录,路径拼接结果会出错。下面是两种精简且健壮的实现方式:

方案1:优化os.walk写法(兼容所有Python3版本)

去掉多余的dirs遍历,用root直接拼接文件名即可,仅需两层循环,_用于占位不需要用到的返回值:

import os

source = r'c:\data\desktop\buildingX\apartments'

for root, _, files in os.walk(source):
    for file in files:
        if file.endswith('.xml'):
            file_path = os.path.join(root, file)
            print(file_path)

如果需要把路径统一收集成列表,还可以用列表推导式进一步简化:

xml_paths = [
    os.path.join(root, file)
    for root, _, files in os.walk(source)
    for file in files
    if file.endswith('.xml')
]

方案2:pathlib实现(Python3.4+推荐,代码更简洁)

pathlib是Python官方推荐的路径处理标准库,用递归glob匹配可以省略所有循环逻辑:

from pathlib import Path

source = Path(r'c:\data\desktop\buildingX\apartments')
# 直接得到Path对象列表,后续做路径操作更方便
xml_paths = list(source.rglob('*.xml'))
# 如果需要字符串格式的完整路径,加转换即可
xml_paths_str = [str(p) for p in source.rglob('*.xml')]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:15:04