Getting a list of all subdirectories in the current directory

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

    This function, with a given parent directory iterates over all its directories recursively and prints all the filenames which it founds inside. Too useful.

    import os
    
    def printDirectoryFiles(directory):
       for filename in os.listdir(directory):  
            full_path=os.path.join(directory, filename)
            if not os.path.isdir(full_path): 
                print( full_path + "\n")
    
    
    def checkFolders(directory):
    
        dir_list = next(os.walk(directory))[1]
    
        #print(dir_list)
    
        for dir in dir_list:           
            print(dir)
            checkFolders(directory +"/"+ dir) 
    
        printDirectoryFiles(directory)       
    
    main_dir="C:/Users/S0082448/Desktop/carpeta1"
    
    checkFolders(main_dir)
    
    
    input("Press enter to exit ;")
    
    

提交回复
热议问题