Python folder names in the directory

前端 未结 8 1108
傲寒
傲寒 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:49

    You can use os.listdir() here a link to the docs

    Warning returns files and directories

    example:

    import os
    
    path = 'pyth/to/dir/'
    dir_list = os.listdir(path)
    

    update: you need to check if the returned names are directories or files

    import os
    
    path = 'pyth/to/dir/'
    # list of all content in a directory, filtered so only directories are returned
    dir_list = [directory for directory in os.listdir(path) if os.path.isdir(path+directory)]
    

提交回复
热议问题