如何在Python中获取n级子目录条目的文件路径?

时间:2015-03-13 11:06:28

标签: python path directory subdirectory os.path

我正在尝试获取特定目录(在Python中)的第n个子目录中的所有文件的文件路径,如下所示:

Directory
   |
   |+ Subdirectory_1
   |       |
   |       |+ Subdirectory_11
   |       |       |
   |       |       |+ ...............       
   |       |       
   |       |                     
   |       |+ Subdirectory_12
   |       |       |
   |       |       |+ ...............       
   |       |       
   |       |+ Subdirectory_13
   |       |       |
   |       |       |+ ...............  
   |       |       
   |       |+ .......................
   |
   |+ Subdirectory_2
   |       |
   |       |+ Subdirectory_21
   |       |       |
   |       |       |+ ...............       
   |       |       
   |       |                     
   |       |+ Subdirectory_22
   |       |       |
   |       |       |+ ...............       
   |       |       
   |       |+ Subdirectory_23
   |       |       |
   |       |       |+ ...............  
   |       |       
   |       |+ .......................
   |
   | ...............................

该列表必须为我提供所有子目录中所有文件的完整文件路径。我试过这样的事情,但它不起作用:

import os
directory_path = os.path.abspath('Directory')
list_folder = [folder for folder in sorted(os.listdir(directory_path)) if os.path.isdir(os.path.join(directory_path, folder))]
list_file = [file for file in sorted(os.listdir(os.path.join(directory_path, list_folder)))]

此外,这只会给我第二级文件,我需要n级子目录。有没有办法根据水平分割路径,例如如果整个路径是:

/home/Directory/Subdirectory_1/Subdirectory_11/Sub_directory_111 .../Subdirectory_n

我需要根据以下级别获取单个文件夹名称:

folder_name(2): Subdirectory_1
folder_name(3): Subdirectory_11
folder_name(3): Sub_directory_111
     :                :
folder_name(n): Subdirectory_n

0 个答案:

没有答案