首页 > 解决方案 > Python: best way to dynamically read folder structure and create list of lists

问题描述

So I have this root folder:

C:\hw

And under this root path I have this folders structure:

C:\hw\ios
    C:\hw\ios\10
    C:\hw\ios\11
    C:\hw\ios\12
    C:\hw\ios\13
    C:\hw\ios\14
C:\hw\android
    C:\hw\android\9
    C:\hw\android\9.0.1

And I want to read all folders into list of lists (only first level):

dict = {
            'ios': ['10', '11', '12', '13', '14'],
            'android': ['9', '9.0.1]
        }

Any suggestions ?

标签: pythonpython-3.x

解决方案


>>> d = {}
>>> BASE_DIR = "."
>>> for file in os.listdir(BASE_DIR):
...     if os.path.isdir(BASE_DIR+file):
...             d[file] = os.listdir(BASE_DIR+file)

如果您只想在该目录中添加文件,则可以添加文件检查的额外条件os.path.isfile()


推荐阅读