1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
#!/usr/bin/env python3
import os
import bisect
pathOfTheDir = "aVousDeMontrerLeChemin..."
# Source :
# http://www.developpez.net/forums/d766118/autres-langages/python-zope/general-python/representer-arbre-console/#post4423332
# http://www.acooke.org/cute/PythonCode0.html
class Tree(object):
__slots__=('tree','files','folders', '__listFormat')
def __init__(self):
self.tree = {}
self.folders = []
self.files = []
self.__listFormat = None
def addFolder(self,name):
self.tree[name]=Tree()
bisect.insort(self.folders,name)
def addFile(self,name):
self.tree[name]=None
bisect.insort(self.files,name)
def addFolders(self,itr):
for x in itr:
self.addFolder(x)
def addFiles(self,itr):
for x in itr:
self.addFiles(x)
def __getitem__(self,key):
return self.tree[key]
def __setitem__(self,key,val):
self.tree[key]=val
def text(self):
iMax = len(self.folders) - 1
containsFiles = bool(self.files)
for i, fold in enumerate(self.folders):
if not containsFiles and i == iMax:
deco = '`'
else:
deco='+'
yield '{0}----[[ {1} ]]'.format(deco, fold)
if containsFiles or i < iMax:
line_next='| '
else:
line_next=' '
for lns in self.tree[fold].text():
yield line_next+lns
if i < iMax:
yield '|'
for file in self.files:
yield '* {0}'.format(file)
def mapFolder(tree, dirname):
'''sert scanner un dossier et ses sous-dossiers et reconstituer leur arbo dans le Tree object passé en param'''
for fnm in os.listdir(dirname):
if os.path.isdir(dirname+os.sep+fnm):
tree.addFolder(fnm)
mapFolder(tree[fnm],dirname+os.sep+fnm)
else:
tree.addFile(fnm)
a=Tree()
mapFolder(a,pathOfTheDir)
print('\n'.join(a.text())) |
Partager