How to get all of the immediate subdirectories in Python

前端 未结 15 1644
旧时难觅i
旧时难觅i 2020-11-29 17:09

I\'m trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions).

I\'m getting bogged down

15条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 17:28

    def get_folders_in_directories_recursively(directory, index=0):
        folder_list = list()
        parent_directory = directory
    
        for path, subdirs, _ in os.walk(directory):
            if not index:
                for sdirs in subdirs:
                    folder_path = "{}/{}".format(path, sdirs)
                    folder_list.append(folder_path)
            elif path[len(parent_directory):].count('/') + 1 == index:
                for sdirs in subdirs:
                    folder_path = "{}/{}".format(path, sdirs)
                    folder_list.append(folder_path)
    
        return folder_list
    

    The following function can be called as:

    get_folders_in_directories_recursively(directory, index=1) -> gives the list of folders in first level

    get_folders_in_directories_recursively(directory) -> gives all the sub folders

提交回复
热议问题