如何用Python获取子目录名称、目录内文件名及对应路径列表
Python生成包含子目录及文件路径的嵌套列表
可以通过Python的os模块实现需求,核心思路是遍历指定根目录下的一级子目录,再逐个收集子目录自身信息和其下的文件信息,最终组合成目标结构。
实现代码
import os def generate_dir_structure(root_dir): result = [] # 遍历根目录下的所有项 for item in os.listdir(root_dir): item_path = os.path.join(root_dir, item) # 仅处理一级子目录 if os.path.isdir(item_path): # 构造子目录的元组(名称,路径) dir_tuple = (item, item_path) file_tuples = [] # 遍历子目录下的文件 for filename in os.listdir(item_path): file_path = os.path.join(item_path, filename) if os.path.isfile(file_path): file_tuples.append((filename, file_path)) # 将目录元组和文件元组组合成子列表,加入结果 result.append([dir_tuple] + file_tuples) return result # 使用示例 if __name__ == "__main__": structure = generate_dir_structure("assets") import pprint pprint.pprint(structure)
代码说明
- 遍历根目录(如
assets)下的所有项目,筛选出其中的一级子目录 - 为每个子目录生成
(目录名, 目录路径)的元组作为子列表的首个元素 - 遍历该子目录下的所有文件,生成
(文件名, 文件路径)的元组并收集 - 将目录元组与文件元组列表组合成子列表,最终汇总为嵌套列表返回
输出结果
运行上述代码后,针对你给出的文件结构,会输出:
[ [ ('location1', 'assets/location1'), ('file1.png', 'assets/location1/file1.png'), ('file2.png', 'assets/location1/file2.png'), ('file3.png', 'assets/location1/file3.png') ], [ ('location2', 'assets/location2'), ('file4.png', 'assets/location2/file4.png'), ('file5.png', 'assets/location2/file5.png') ] ]
内容的提问来源于stack exchange,提问作者TranquilityEden
相关产品推荐
相关产品推荐

