Fonction "tree" pour Windows
Posté le jeu. 22 août 2019 dans Python
from pathlib import Path
import stat
try:
from colorama import init, Fore, Back, Style
init()
DIR_COLOR = Fore.BLUE + Style.BRIGHT
EXE_COLOR = Fore.GREEN + Style.BRIGHT
RESET_COLOR = Style.RESET_ALL
except (ModuleNotFoundError, ImportError):
DIR_COLOR = EXE_COLOR = RESET_COLOR = ''
def tree(directory, print_files=False, show_hidden=False):
def _color_(path):
if str(path) == '.':
return DIR_COLOR + '.' + RESET_COLOR
if path.is_dir():
return DIR_COLOR + path.name + RESET_COLOR
if path.stat()[stat.ST_MODE] & (
stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH):
return EXE_COLOR + path.name + RESET_COLOR
return path.name
def _tree_symbol_(is_last):
return '└── ' if is_last else '├── '
def _tree_(directory, print_files, show_hidden, padding='', is_last=False, is_first=True):
if is_first:
print(_color_(directory))
else:
print(padding[:-1] + _tree_symbol_(is_last) + _color_(directory))
files = [f for f in directory.iterdir()
if ((show_hidden or not f.name.startswith('.'))
and (print_files or f.is_dir()))]
padding = padding + ' ' * (not is_first)
files = sorted(files, key=lambda s: s.name.lower())
count = 0
last = len(files) - 1
for i, file in enumerate(files):
count += 1
is_last = i == last
if file.is_dir():
if count == len(files):
new_padding = padding + ' '
else:
new_padding = padding + '│'
_tree_(file, print_files, show_hidden, new_padding,
is_last, False)
else:
print(padding + _tree_symbol_(is_last) + _color_(file))
_tree_(directory, print_files, show_hidden)
# Example
tree(Path(), print_files=True)