Skip to content

Instantly share code, notes, and snippets.

@icanwalkonwater
Last active August 29, 2018 16:53
Show Gist options
  • Save icanwalkonwater/3e954486f8e325d3eaa83230098c04ea to your computer and use it in GitHub Desktop.
Save icanwalkonwater/3e954486f8e325d3eaa83230098c04ea to your computer and use it in GitHub Desktop.
Print a tree of your folder and its subfolders and files.
#!/bin/python
import os
PREFIX_LINE = '+--- '
PREFIX_END = '\--- '
SPACE = ' '
def main():
global hidden
hidden = input('List hidden files ? (default: True): ')
if len(hidden) == 0 or hidden.lower() == 'true':
hidden = True
else:
hidden = False
global max_depth
max_depth = input('Max depth ? (default: infinite): ')
if len(max_depth) == 0 or max_depth.lower() == 'infinite':
max_depth = None
else:
max_depth = int(max_depth)
print_line(os.getcwd())
print_path(os.getcwd())
def print_dir(folder: os.DirEntry, depth: int = 0, last: bool = False):
if folder.name[0] is '.' and not hidden:
return
if max_depth is not None and depth >= max_depth:
print_line(folder.name, depth, last)
print_max_depth(depth + 1)
return
try:
if folder.is_symlink():
print_symlink(folder.name, os.readlink(folder.path), depth)
else:
print_line(folder.name, depth, last)
print_path(folder.path, depth)
except PermissionError:
print_permission(depth)
def print_path(path: str, depth: int = 0):
with os.scandir(path) as scan:
subs = [f for f in scan]
sub_folders = sorted([f for f in subs if f.is_dir()], key=lambda d: d.name)
files = sorted([f for f in subs if f.is_file()], key=lambda f: f.name)
folder_amount = len(sub_folders)
files_amount = len(files)
for i in range(1, folder_amount + 1):
print_dir(sub_folders[i - 1], depth + 1, True if i == folder_amount and files_amount == 0 else False)
for i in range(1, files_amount + 1):
if not hidden and files[i - 1].name.startswith('.'):
continue
print_line(files[i - 1].name, depth + 1, True if i == files_amount else False)
def print_line(name: str, depth: int = 0, last: bool = False):
print((depth * SPACE) + (PREFIX_END if last else PREFIX_LINE) + name)
def print_symlink(name: str, dest: str, depth: int = 0, last: bool = False):
print((depth * SPACE) + (PREFIX_END if last else PREFIX_LINE) + name + ' --> ' + dest)
def print_permission(depth: int = 0):
print((depth * SPACE) + PREFIX_END + 'Permission denied.')
def print_max_depth(depth: int = 0):
print((depth * SPACE) + PREFIX_END + 'Max depth reached !')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment