
The Problem: Documenting Your Project Structure
If you’ve ever needed to document your project’s file structure in a README or share it with team members, you know how tedious it can be to manually create those nice tree diagrams. Something like this:
DepthAnythingv2/
├── main.py
├── depth_anything_v2_gui.py
├── tiling_depth_anything_v2.py
├── depth_anything_v2_model.py
├── models/
│ ├── __init__.py
│ ├── depth_anything.py
│ ├── depth_anything_v2_vits.pth
│ ├── depth_anything_v2_vitb.pth
│ └── depth_anything_v2_vitl.pth
Sure, there are CLI tools like tree
on Linux/macOS, but they might not be available on all platforms, and customizing their output can be tricky. Plus, GUI solutions are often more accessible for many users.
So I decided to build a cross-platform, user-friendly solution to generate these directory structures with full customization options and Markdown-friendly output.
Introducing the Directory Structure Generator
The Directory Structure Generator is a Python application with a clean GUI that allows you to:
- Select any directory on your system
- Set a maximum depth for traversal
- Exclude files/folders with regex patterns
- Include or exclude hidden files
- Copy the generated structure to your clipboard
- Save the output directly to a Markdown file
Best of all, it can be packaged as a standalone executable, making it easy to share with colleagues who might not have Python installed.
How It Works: The Core Algorithm
At the heart of the application is a recursive algorithm that traverses your directory structure:
def generate_directory_structure(self, directory, max_depth, exclude_pattern, include_hidden):
"""Generate a markdown directory structure."""
# Get the base directory name
base_name = os.path.basename(directory)
# Compile the exclude pattern regex
exclude_regex = re.compile(exclude_pattern) if exclude_pattern else None
# Start with the base directory
result = [f"{base_name}/"]
# Call the recursive function to build the tree
self._build_tree(directory, "", max_depth, 0, result, exclude_regex, include_hidden)
return "\n".join(result)
The _build_tree
function does the heavy lifting by recursively exploring subdirectories:
def _build_tree(self, directory, prefix, max_depth, current_depth, result, exclude_regex, include_hidden):
"""Recursively build the directory tree."""
if current_depth >= max_depth:
return
# Get all items in the directory
try:
items = sorted(os.listdir(directory))
except PermissionError:
result.append(f"{prefix}├── [Permission Denied]")
return
# Filter out excluded items
filtered_items = []
for item in items:
# Skip hidden files/folders if not included
if not include_hidden and item.startswith('.'):
continue
# Skip items matching exclude pattern
if exclude_regex and exclude_regex.search(item):
continue
filtered_items.append(item)
# Process each item
for i, item in enumerate(filtered_items):
is_last = (i == len(filtered_items) - 1)
item_path = os.path.join(directory, item)
# Choose the appropriate prefix
if is_last:
branch = "└── "
new_prefix = prefix + " "
else:
branch = "├── "
new_prefix = prefix + "│ "
# Add the item to the result
if os.path.isdir(item_path):
result.append(f"{prefix}{branch}{item}/")
self._build_tree(item_path, new_prefix, max_depth, current_depth + 1, result, exclude_regex, include_hidden)
else:
result.append(f"{prefix}{branch}{item}")
This algorithm creates those beautiful tree structures with the correct branch characters (├, └, │) that make directory trees so readable.
The User Interface
For the UI, I used Tkinter, Python’s standard GUI toolkit, which ensures compatibility across platforms. The interface is straightforward:
The main components include:
- Directory selection with a browse button
- Options panel for customization
- Large output area with scrolling
- Action buttons (Copy, Save, Clear)
- Status bar for feedback
Making It Portable
One of the biggest challenges was making the application portable. I explored three approaches:
1. Standalone Executable with PyInstaller
This is the most user-friendly approach for distribution. The application is packaged into a single executable file that runs on any computer with the same OS, no Python installation required:
import PyInstaller.__main__
import os
import platform
# Build command
build_args = [
'directory_structure_to_md.py',
'--onefile',
'--windowed',
'--name=DirectoryStructureGenerator',
'--clean',
]
# Run PyInstaller
PyInstaller.__main__.run(build_args)
2. Self-Contained Python Script
For more technical users who have Python installed, I created a version that only uses standard library modules. This removes the need for installing additional packages:
# Instead of using pyperclip for clipboard operations
self.root.clipboard_clear()
self.root.clipboard_append(text)
3. Web Application Version
For maximum portability, I also developed a web application version using Flask. This allows users to access the tool through a browser, which can be particularly useful in team environments:
from flask import Flask, render_template, request, jsonify
import os
import re
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate', methods=['POST'])
def generate_structure():
# Get the form data and generate structure
directory = request.form['directory']
# ...
return jsonify({'structure': structure})
Real-World Use Cases
I’ve found this tool invaluable for:
- Documentation – Adding directory structures to README files and documentation
- Code Reviews – Providing a quick overview of project organization when submitting PRs
- Teaching – Helping students understand project structures in tutorials
- Planning – Visualizing project organization before implementation
Pro Tips
- Default Exclusions: The default exclude pattern (
__pycache__|\.git|\.venv|\.idea|\.vscode|node_modules
) helps keep your structure clean by omitting common non-essential directories. - Depth Control: For large projects, start with a lower max depth (like 3) to get an overview, then increase if needed.
- Custom Patterns: You can create custom exclude patterns for specific project types. For example, in a Python project:
\.pyc$|__pycache__|\.egg-info
.
Next Steps and Improvements
While the current tool meets my needs, there are several enhancements I’m considering:
- Color Coding – Adding syntax highlighting to differentiate files and directories
- Export Formats – Supporting additional formats like HTML or JSON
- Folder Size Information – Including file/folder sizes in the output
- File Type Grouping – Organizing files by type in the display
- Integration with Git – Adding indicators for modified/untracked files
Download Portable exe version:
Download “Directory Structure Generator” DirectoryStructureGenerator.zip – Downloaded 0 times – 38.23 MB