Python folder names in the directory

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

    Python 3.x: If you want only the directories in a given directory, try:

    import os
    search_path = '.'   # set your path here.
    root, dirs, files = next(os.walk(search_path), ([],[],[]))
    print(dirs)
    

    The above example will print out a list of the directories in the current directory like this:

    ['dir1', 'dir2', 'dir3']
    

    The output contains only the sub-directory names.
    If the directory does not have sub-directories, it will print:

    []
    

    os.walk() is a generator method, so use next() to only call it once. The 3-tuple of empty strings is for the error condition when the directory does not contain any sub-directories because the os.walk() generator returns 3-tuples for each layer in the directory tree. Without those, if the directory is empty, next() will raise a StopIteration exception.

    For a more compact version:

    dirs = next(os.walk(search_path), ([],[],[]))[1]
    
    0 讨论(0)
  • 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)]
    
    0 讨论(0)
提交回复
热议问题