Skip to content

Instantly share code, notes, and snippets.

Last active September 19, 2021 20:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Python script to create a Markdown representation of a directory tree
#!/usr/bin/env python3
# Walks a directory tree, creating a Markdown representation of it.
# First command line argumaent is root directory. Defaults to current directory.
import os
import sys
if len(sys.argv) > 1:
path = sys.argv[1]
path = "."
indent = "\t"
item_prefix = "* "
def scan_directory(path, prefix=indent):
"""Print contents of a directory with specified prefix before each line.
Files are printed first, followed by subdirectories and their contents with
additional indentation.
Ignores any files or directories with names starting with ".".
with os.scandir(path) as it:
entries = [entry for entry in list(it) if not".")]
files = [entry for entry in entries if entry.is_file()]
files.sort(key=lambda entry:
for file in files:
print("{}{}`{}`".format(prefix, item_prefix,
dirs = [entry for entry in entries if entry.is_dir()]
dirs.sort(key=lambda entry:
for dir in dirs:
print("{}{}`{}/`".format(prefix, item_prefix,
scan_directory(dir.path, prefix + indent)
print("{}`{}/`".format(item_prefix, path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment