I made a function to output the tree structure of files and directories on Python like a tree of commands, so make a note.
Give the following function the path of the directory you want to display in the tree. Since it is implemented for Mac, it is not supported when paths are not separated by slashes.
import pathlib
import glob
import os
def tree(path, layer=0, is_last=False, indent_current=' '):
if not pathlib.Path(path).is_absolute():
path = str(pathlib.Path(path).resolve())
#View current directory
current = path.split('/')[::-1][0]
if layer == 0:
print('<'+current+'>')
else:
branch = '└' if is_last else '├'
print('{indent}{branch}<{dirname}>'.format(indent=indent_current, branch=branch, dirname=current))
#Get the path of the lower hierarchy
paths = [p for p in glob.glob(path+'/*') if os.path.isdir(p) or os.path.isfile(p)]
def is_last_path(i):
return i == len(paths)-1
#Display recursively
for i, p in enumerate(paths):
indent_lower = indent_current
if layer != 0:
indent_lower += ' ' if is_last else '│ '
if os.path.isfile(p):
branch = '└' if is_last_path(i) else '├'
print('{indent}{branch}{filename}'.format(indent=indent_lower, branch=branch, filename=p.split('/')[::-1][0]))
if os.path.isdir(p):
tree(p, layer=layer+1, is_last=is_last_path(i), indent_current=indent_lower)
For example, consider the case where the directory called Test is configured as follows.
When tree is executed at this time, it looks like this.
tree('/hogehoge/Test')
Output result
<Test>
├<Test_01>
│ ├ccccc.txt
│ └bbbbb.txt
├<Test_02>
├<Test_03>
└aaaaa.txt
The result is the same even if you specify it with a relative path.
tree('./') # /hogehoge/Run with Test
Output result
<Test>
├<Test_01>
│ ├ccccc.txt
│ └bbbbb.txt
├<Test_02>
├<Test_03>
└aaaaa.txt
Recommended Posts