Getting a list of all subdirectories in the current directory

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

    Function to return a List of all subdirectories within a given file path. Will search through the entire file tree.

    import os
    
    def get_sub_directory_paths(start_directory, sub_directories):
        """
        This method iterates through all subdirectory paths of a given 
        directory to collect all directory paths.
    
        :param start_directory: The starting directory path.
        :param sub_directories: A List that all subdirectory paths will be 
            stored to.
        :return: A List of all sub-directory paths.
        """
    
        for item in os.listdir(start_directory):
            full_path = os.path.join(start_directory, item)
    
            if os.path.isdir(full_path):
                sub_directories.append(full_path)
    
                # Recursive call to search through all subdirectories.
                get_sub_directory_paths(full_path, sub_directories)
    
    return sub_directories
    

提交回复
热议问题