Last active
September 12, 2020 08:29
-
-
Save meatyite/88c00854533c9adcb098e49b77dfbf2f to your computer and use it in GitHub Desktop.
HTML directory tree generator (python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
################################### | |
# Licensed under the UNLICENSE # | |
# See unlicense.org for more info # | |
################################### | |
# usage: html-tree.py > output.html OR html-tree.py [path] > output.html | |
import functools | |
import os | |
from os.path import abspath | |
import sys | |
print("""<!DOCTYPE html>\ | |
<html> | |
<body> | |
""") | |
def get_directory_structure(root_dir): | |
""" | |
Creates a nested dictionary that represents the folder structure of root_dir | |
""" | |
dir = {} | |
root_dir = root_dir.rstrip(os.sep) | |
start = root_dir.rfind(os.sep) + 1 | |
for path, dirs, files in os.walk(root_dir): | |
folders = path[start:].split(os.sep) | |
subdir = dict.fromkeys(files) | |
parent = functools.reduce(dict.get, folders[:-1], dir) | |
parent[folders[-1]] = subdir | |
return dir | |
path_to_list = "" | |
if len(sys.argv) >= 2: | |
path_to_list = sys.argv[1] | |
else: | |
path_to_list = "./" | |
path_to_list = abspath(path_to_list) | |
dir_struct = get_directory_structure(path_to_list) | |
num_of_recursions = 1 | |
def recurse_html(dir_dict): | |
global num_of_recursions | |
recursion_limit = sys.getrecursionlimit() | |
if recursion_limit == num_of_recursions - 2: | |
sys.setrecursionlimit(recursion_limit + 1) | |
num_of_recursions += 1 | |
print('\n<ul>', end='') | |
for file_or_folder in dir_dict.keys(): | |
if dir_dict[file_or_folder] is not None: | |
print('\n<p>' + file_or_folder + '</p>', end='') | |
recurse_html(dir_dict[file_or_folder]) | |
else: | |
print('\n<li>' + file_or_folder + '</li>', end='') | |
print('\n</ul>', end='') | |
recurse_html(dir_struct) | |
print('\n</body>\n</html>', end='') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment