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

Python如何获取包含子目录的文件完整绝对路径

解决方案

你可以提前遍历根目录构建「文件名→完整绝对路径」的映射字典,os.walk逻辑仅执行一次,不会嵌套在业务函数内部,不会增加函数嵌套层级,后续查询路径直接查字典即可,执行效率更高。

完整修改后代码

import os

mother_path = r'c:\data\user1\Desktop\mother_directory'

blue_dates = ['20211011', '20211012', '20211013', '20211001', '20211002']
red_dates =  ['20211011', '20211009', '20211008', '20211001', '20211002']
file_names = ['20211011.xml', '20211001.xml', '20211002.xml']

# 提前构建文件名到完整路径的映射字典
file_path_map = {}
for root, _, files in os.walk(mother_path):
    for file in files:
        if file in file_names:
            file_path_map[file] = os.path.join(root, file)

def process_files(x):
    if x in red_dates:
        match_file = [s for s in file_names if x in s]
        if match_file and match_file[0] in file_path_map:
            file_path = file_path_map[match_file[0]]
            print(file_path)

for x in blue_dates:
    process_files(x)

运行输出

c:\data\user1\Desktop\mother_directory\child1\20211011.xml
c:\data\user1\Desktop\mother_directory\child1\20211001.xml
c:\data\user1\Desktop\mother_directory\child2\20211002.xml

方案说明

  • 目录遍历逻辑仅在程序初始化阶段执行1次,不会嵌套进process_files函数,完全满足你不希望提升函数嵌套层级的要求
  • 后续路径查询为O(1)复杂度的字典查找,相比每次遍历目录效率更高
  • 新增了空值判断逻辑,避免出现匹配不到文件时报错的问题

内容的提问来源于stack exchange,提问作者Al-Andalus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:06:06