Getting a list of all subdirectories in the current directory

后端 未结 29 2702
一个人的身影
一个人的身影 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: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.

提交回复
热议问题