Python folder names in the directory

前端 未结 8 1168
傲寒
傲寒 2020-12-23 23:15

how can i get the folder names existing in a directory using Python ?

I want to save all the subfolders into a list to work with the names after that but i dont know

8条回答
  •  死守一世寂寞
    2020-12-23 23:41

    You can use os.walk()

    # !/usr/bin/python
    
    import os
    
    directory_list = list()
    for root, dirs, files in os.walk("/path/to/your/dir", topdown=False):
        for name in dirs:
            directory_list.append(os.path.join(root, name))
    
    print directory_list
    

    EDIT

    If you only want the first level and not actually "walk" through the subdirectories, it is even less code:

    import os
    
    root, dirs, files = os.walk("/path/to/your/dir").next()
    print dirs
    

    This is not really what os.walk is made for. If you really only want one level of subdirectories, you can also use os.listdir() like Yannik Ammann suggested:

    root='/path/to/my/dir'
    dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
    print dirlist
    

提交回复
热议问题