How do I implemet an Hierarchical Tree using python?

83 Views Asked by At

I'm working on a project that need to return a list of all the leafs (files) in a Tree. I don't know how to start and I need some help :)

I need to create a program that return all the files and folders in a current folder that running a process (my_program.py), the results should contain the root folder, files, subfolders and subfolders.files etc....

2

There are 2 best solutions below

2
Poonam On BEST ANSWER
import os
##Provide value of a path in filepath variable
filepath="C:\Users\poonamr\Desktop"
for path, dirs, files in os.walk(os.path.abspath(filepath)):
    print path
    if len(dirs)==0:
        print('No directories available in "' + path + '"')
    else:
        print dirs
    if len(files)==0:
        print('No files available in "' + dirs + '"') 
    else:
        print files
    print "\n"
0
Poonam On
import os

def FileTree(Original_Path):
    dirlist=[]
    filelist=[]
    for dirnm in os.listdir(Original_Path):
        if os.path.isdir(Original_Path + "\\" + dirnm):
            dirlist.append(dirnm)
        else:
             filelist.append(dirnm)
    print "Folder    : " , Original_Path
    print "SubFolder : " , dirlist
    print "Files     : " , filelist
    print "\n\n"
    for dirSub in dirlist:
        FileTree(Original_Path+ "\\" + dirSub + "\\")


##Path specification    
Original_Path="C:\Users\poonamr\Desktop\Python Programs"
FileTree(Original_Path)