Заметка Красивый вывод структуры каталогов

  • Автор темы Автор темы explorer
  • Дата начала Дата начала
Темы, которые НЕ подходят по объему под префикс "Статья"

explorer

Well-known member
05.08.2018
1 074
2 470
Всем привет!

Нашёл на просторах интернета скрипт создающий дерево каталогов и файлов. Немного переделал, упростил и добавил красоты в виде вывода с иконками и цветным текстом директорий. В 32 строке программы впишите свой путь, или просто замените на инпут. Цвета можно менять на те, что поддерживает модуль, смотреть

Код программы:
Python:
from pathlib import Path
from itertools import islice
from colorama import Fore, Style

space = '   '
apeak = '│  '
sprig = ['├──']
later = ['└──']
files = 0
directories = 0


def tree(current_folder: Path, only_dir: bool = False, prefix: str = ''):
    global files, directories
    if only_dir:
        scope = [x for x in current_folder.iterdir() if x.is_dir()]
    else:
        scope = list(current_folder.iterdir())
    scope.sort()
    building = list(zip(sprig * (len(scope) - 1) + later, scope))
    for pointer, path in building:
        if path.is_dir():
            yield prefix + pointer + "\U0001F4C2 " + Fore.LIGHTBLUE_EX + Style.BRIGHT + path.name + Fore.RESET
            directories += 1
            extension = apeak if pointer == sprig[0] else space
            yield from tree(path, prefix=prefix + extension)
        elif not only_dir:
            yield prefix + pointer + "\U0001F4C4 " + Fore.LIGHTGREEN_EX + Style.BRIGHT + path.name + Fore.RESET
            files += 1


folder = Path('/home/explorer/LearnQA_Docker')
print(Fore.LIGHTBLUE_EX + Style.BRIGHT + folder.name + Fore.RESET)
iterator = tree(folder)
for line in islice(iterator, 500):
    print(line)
print(f'\n{directories} directories' + (f', {files} files' if files else ''))

Результат выполнения программы:

54545.png


Для линукс существует пакет tree, ставится pip install tree

Для сравнения вывод tree:

65.png


С иконками смотрится симпатичнее )
 

Парни, вы серьёзно думаете, что стандартные команды линукса делают тоже самое? Вообще не то пальто и разные задачи. Данный скрипт отлично вписывается для визуального представления проекта при программировании, или локального сайта и т.д. и т.п.
 
Вот реализация сштатными средствами если на проде запрещён питон:

Bash:
#!/bin/bash

# Colors and styles
BLUE="\033[1;94m"
GREEN="\033[1;92m"
RESET="\033[0m"
BOLD="\033[1m"

# Counters
FILES=0
DIRECTORIES=0
LINE_COUNT=0
MAX_LINES=500

# Symbols
FOLDER_ICON="📁 "
FILE_ICON="📄 "
VERTICAL="│  "
BRANCH="├──"
LAST="└──"
SPACE="   "

# Recursive tree function
tree() {
    local dir="$1"
    local prefix="$2"
    local only_dir="$3"

    # Read directory contents
    local items=()

    if [ "$only_dir" = true ]; then
        items=( "$dir"/*/ )
    else
        items=( "$dir"/* )
    fi

    # Filter and sort
    items=($(printf "%s\n" "${items[@]}" | sort))

    local count=${#items[@]}
    local idx=0

    for item in "${items[@]}"; do
        ((idx++))

        # Check line limit
        if [ $LINE_COUNT -ge $MAX_LINES ]; then
            return
        fi

        # Handle naming
        local name=$(basename "$item")
        local pointer="${BRANCH}"

        [ $idx -eq $count ] && pointer="${LAST}"

        # Directory handling
        if [ -d "$item" ]; then
            ((DIRECTORIES++))
            echo -e "${prefix}${pointer} ${BLUE}${BOLD}${FOLDER_ICON}${name}${RESET}"
            ((LINE_COUNT++))

            # Recursive call
            local new_prefix="${prefix}$( ([ $idx -ne $count ] && echo "${VERTICAL}") || echo "${SPACE}")"
            tree "$item" "$new_prefix" "$only_dir"

        # File handling (if not only_dir mode)
        elif [ "$only_dir" = false ]; then
            ((FILES++))
            echo -e "${prefix}${pointer} ${GREEN}${BOLD}${FILE_ICON}${name}${RESET}"
            ((LINE_COUNT++))
        fi
    done
}

# Main script
if [ $# -eq 0 ]; then
    target="."
else
    target="$1"
fi

only_dir=false

if [ "$2" = "--only-dir" ]; then
    only_dir=true
fi

# Check if directory exists
if [ ! -d "$target" ]; then
    echo "Error: Directory does not exist"
    exit 1
fi

# Print header
echo -e "${BLUE}${BOLD}$(basename "$(realpath "$target")")${RESET}"

# Start recursion
tree "$(realpath "$target")" "" "$only_dir"

# Print summary
echo -e "\n${DIRECTORIES} directories"$([ "$only_dir" = false ] && echo ", ${FILES} files")\

1745315191522.webp
 
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!