1
+ #Directory Tree Generator
2
+
3
+ import os
4
+ import argparse
5
+
6
+ def realname (path , root = None ):
7
+ if root is not None :
8
+ path = os .path .join (root , path )
9
+ result = os .path .basename (path )
10
+ if os .path .islink (path ):
11
+ realpath = os .readlink (path )
12
+ result = '%s -> %s' % (os .path .basename (path ), realpath )
13
+ return result
14
+
15
+ def ptree (startpath , depth = - 1 ):
16
+ prefix = 0
17
+ assert os .path .isdir (startpath ),"Directory not valid"
18
+ if startpath != '/' :
19
+ if startpath .endswith ('/' ): startpath = startpath [:- 1 ]
20
+ prefix = len (startpath )
21
+ for root , dirs , files in os .walk (startpath ):
22
+ level = root [prefix :].count (os .sep )
23
+ if depth > - 1 and level > depth : continue
24
+ indent = subindent = ''
25
+ if level > 0 :
26
+ indent = '| ' * (level - 1 ) + '|-- '
27
+ subindent = '| ' * (level ) + '|-- '
28
+ print ('{}{}/' .format (indent , realname (root )))
29
+
30
+ for d in dirs :
31
+ if os .path .islink (os .path .join (root , d )):
32
+ print ('{}{}' .format (subindent , realname (d , root = root )))
33
+ for f in files :
34
+ print ('{}{}' .format (subindent , realname (f , root = root )))
35
+
36
+ if __name__ == '__main__' :
37
+
38
+
39
+ print ("\n Directory tree \n " )
40
+
41
+ parser = argparse .ArgumentParser (description = 'prints directory tree.' )
42
+ parser .add_argument ('startpath' , type = str ,
43
+ help = 'path to stating directory' )
44
+ args = parser .parse_args ()
45
+ argsd = vars (args )
46
+ ptree (** argsd )
47
+
48
+ input ("\n \n Press enter to exit" )
0 commit comments