Python implementation directory tree generation sample _python

Source: Internet
Author: User

Copy Code code as follows:

#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import OS
Import Optparse

Location_none = ' NONE '
Location_mid = ' MID '
Location_mid_gap = ' Mid_gap '
Location_tail = ' TAIL '
Location_tail_gap = ' Tail_gap '

notations = {
Location_none: ',
Location_mid: ' ├─ ',
Location_mid_gap: ' │ ',
Location_tail: ' └─ ',
Location_tail_gap: '
}

Class Node (object):
    def __init__ (self, name, depth, Parent=none, Location=location_none):
        self.name = name
        self.depth = Depth
        self.parent = parent
         self.location = Location
        self.children = []

    def __str__ (self):
        sections = [Self.name]
        parent = self.has_parent ()
         If Parent:
            if Self.is_tail ():
                Sections.insert (0, Notations[location_tail])
            else:
                 Sections.insert (0, Notations[location_mid])
            Self.__insert_ Gaps (self, sections)
        return ". Join (sections)

    def __insert_gaps (Self, node, sections):
        Parent = Node.has_parent ()
        # Parent exists and parent ' s not ' root node
        If Parent and Parent.has_parent ():
             if Parent.is_tail ():
                 sections.insert (0, Notations[location_tail_gap])
             Else:
                 sections.insert (0, Notations[location_mid_gap])
             Self.__insert_gaps (parent, sections)

def has_parent (self):
Return self.parent

def has_children (self):
Return Self.children

def add_child (Self, node):
Self.children.append (node)

def is_tail (self):
return self.location = = Location_tail

Class Tree (Object):
def __init__ (self):
Self.nodes = []

def debug_print (self):
For node in Self.nodes:
Print (str (node) + '/')

def write2file (self, filename):
Try
with open (filename, ' W ') as FP:
Fp.writelines (str (node) + '/\n '
For node in self.nodes)
Except IOError as E:
Print (e)
return 0
Return 1

def build (self, path):
Self.__build (path, 0, None, Location_none)

    def __build (self, path, depth, parent, location):
         If Os.path.isdir (path):
            name = Os.path.basename (path)
            node = node (name, Depth, parent, location)
            self.add_node (node
            If Parent:
                 parent.add_child (node)

            entries = self.list_folder (path)
             end_index = len (entries)-1
             for I, entry in enumerate (entries):
                 Childpath = os.path.join (path, entry)
                 location = Location_tail if i = = End_index Else Location_mid
                 Self.__build (Childpath, depth + 1, node, location)

def list_folder (self, Path):
"" "Folders only." "
return [D to D in Os.listdir (path) if Os.path.isdir (Os.path.join (path, D))]
# for entry in Os.listdir (path):
# Childpath = os.path.join (path, entry)
# if Os.path.isdir (Childpath):
# Yield Entry

def add_node (Self, node):
Self.nodes.append (node)

Def _parse_args ():
    parser = optparse. Optionparser ()
    parser.add_option (
        ' P ', '-- Path ', dest= ' path ', action= ' store ', type= ' string ',
        default= './', help = ' path to generate ' [Default:%default] ']
    parser.add_option (
   & nbsp;    '-o ', '--out ', dest= ' file ', action= ' store ', type= ' string ',
         help= ' The file to save [Default:pathname.trees] ']
    options, args = par Ser.parse_args ()
    # positional arguments are ignored
    return options

Def main ():
    options = _parse_args ()
    path = Options.path
     if not Os.path.isdir (path):
        print ('%s isn't a directory '% Path)
        return 2

If not path or path = = './':
filepath = Os.path.realpath (__file__) # for Linux
Path = Os.path.dirname (filepath)
Tree = Tree ()
Tree.build (PATH)
# Tree.debug_print ()
If Options.file:
filename = Options.file
Else
Name = Os.path.basename (path)
filename = '%s.trees '% name
return tree.write2file (filename)

if __name__ = = ' __main__ ':
Import Sys
Sys.exit (Main ())

Run effect

Copy Code code as follows:

gtest_start/
├─build/
├─lib/
│└─gtest/
├─output/
│├─primer/
││├─debug/
│││├─lib/
│││└─obj/
││└─release/
││├─lib/
││└─obj/
│└─thoughts/
│├─debug/
││├─lib/
││└─obj/
│└─release/
│├─lib/
│└─obj/
├─src/
│├─primer/
│└─thoughts/
├─test/
│├─primer/
│└─thoughts/
├─third_party/
│└─gtest/
└─tools/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.