Getting a list of all subdirectories in the current directory

后端 未结 29 2331
一个人的身影
一个人的身影 2020-11-22 08:02

Is there a way to return a list of all the subdirectories in the current directory in Python?

I know you can do this with files, but I need to get the list of direct

相关标签:
29条回答
  • 2020-11-22 08:39

    Here are a couple of simple functions based on @Blair Conrad's example -

    import os
    
    def get_subdirs(dir):
        "Get a list of immediate subdirectories"
        return next(os.walk(dir))[1]
    
    def get_subfiles(dir):
        "Get a list of immediate subfiles"
        return next(os.walk(dir))[2]
    
    0 讨论(0)
  • 2020-11-22 08:41
    import os
    
    d = '.'
    [os.path.join(d, o) for o in os.listdir(d) 
                        if os.path.isdir(os.path.join(d,o))]
    
    0 讨论(0)
  • 2020-11-22 08:41

    This will list all subdirectories right down the file tree.

    import pathlib
    
    
    def list_dir(dir):
        path = pathlib.Path(dir)
        dir = []
        try:
            for item in path.iterdir():
                if item.is_dir():
                    dir.append(item)
                    dir = dir + list_dir(item)
            return dir
        except FileNotFoundError:
            print('Invalid directory')
    

    pathlib is new in version 3.4

    0 讨论(0)
  • 2020-11-22 08:41

    This should work, as it also creates a directory tree;

    import os
    import pathlib
    
    def tree(directory):
        print(f'+ {directory}')
        print("There are " + str(len(os.listdir(os.getcwd()))) + \
        " folders in this directory;")
        for path in sorted(directory.glob('*')):
            depth = len(path.relative_to(directory).parts)
            spacer = '    ' * depth
            print(f'{spacer}+ {path.name}')
    

    This should list all the directories in a folder using the pathlib library. path.relative_to(directory).parts gets the elements relative to the current working dir.

    0 讨论(0)
  • 2020-11-22 08:42

    With full path and accounting for path being ., .., \\, ..\\..\\subfolder, etc:

    import os, pprint
    pprint.pprint([os.path.join(os.path.abspath(path), x[0]) \
        for x in os.walk(os.path.abspath(path))])
    
    0 讨论(0)
提交回复
热议问题