Python implementation directory tree generation example

Source: Internet
Author: User
Copy CodeThe code is 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 parent is not the 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 for 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= ' the path to generate the tree [default:%default] ')
Parser.add_option (
'-O ', '--out ', dest= ' file ', action= ' store ', type= ' string ',
Help= ' The file to save the result [Default:pathname.trees] ')
Options, args = Parser.parse_args ()
# positional arguments is ignored
Return options

def main ():
options = _parse_args ()
Path = Options.path
If not Os.path.isdir (path):
Print ('%s is not 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 the 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.