Getting a list of all subdirectories in the current directory

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

    Lot of nice answers out there but if you came here looking for a simple way to get list of all files or folders at once. You can take advantage of the os offered find on linux and mac which and is much faster than os.walk

    import os
    all_files_list = os.popen("find path/to/my_base_folder -type f").read().splitlines()
    all_sub_directories_list = os.popen("find path/to/my_base_folder -type d").read().splitlines()
    

    OR

    import os
    
    def get_files(path):
        all_files_list = os.popen(f"find {path} -type f").read().splitlines()
        return all_files_list
    
    def get_sub_folders(path):
        all_sub_directories_list = os.popen(f"find {path} -type d").read().splitlines()
        return all_sub_directories_list
    

提交回复
热议问题