Search code examples
pythonhierarchical-trees

How do I implemet an Hierarchical Tree using python?


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....


Solution

  • 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"