Skip to content

Instantly share code, notes, and snippets.

@esafwan
Created April 16, 2024 05:16
Show Gist options
  • Save esafwan/106ce2623da4725930fabd23c8007e48 to your computer and use it in GitHub Desktop.
Save esafwan/106ce2623da4725930fabd23c8007e48 to your computer and use it in GitHub Desktop.
Output directory tree as text with python

Python code for displaying the directory structure of a specific directory. It allows users to view the contents of a directory up to two levels deep, organizing and listing all subdirectories and files neatly.

Example Use Case:

Imagine you have a project directory for a web application, and you want to quickly understand how the files and folders are organized within this directory without diving into each folder manually. You can use this script to print out a structured list of all the directories and files, up to two levels deep.

Directory Structure Example:

Suppose your project directory is structured as follows:

/myproject/
  /app/
    app.py
    config.py
  /templates/
    index.html
    login.html
  /static/
    /css/
      style.css
    /js/
      app.js
  requirements.txt
  README.md

When you run the script targeting the /myproject/ directory, it outputs:

/myproject/
--app/
  --app.py
  --config.py
--templates/
  --index.html
  --login.html
--static/
  --css/
  --js/
--requirements.txt
--README.md

This output shows the main directories (app, templates, static) and files (requirements.txt, README.md) directly under /myproject/, as well as contents up to two levels deep, such as the files in app and templates, and the subdirectories under static.

Utility and Customization:

This script is particularly useful for developers or system administrators who need to quickly document or review the structure of a project's directories. It can be customized further to adjust the depth of the directory tree shown or to filter out specific types of files or directories, making it a versatile tool for managing and navigating file systems.

import os
def print_directory(path, prefix=''):
# Check the depth from the prefix, each "--" represents a level deeper
if prefix.count('--') >= 2:
return
try:
entries = os.listdir(path)
except PermissionError:
print(f"{prefix}{os.path.basename(path)}/ [Permission Denied]")
return
entries = sorted(entries) # Sort to maintain consistent order
directories = [entry for entry in entries if os.path.isdir(os.path.join(path, entry))]
files = [entry for entry in entries if os.path.isfile(os.path.join(path, entry))]
# Print directories first
for directory in directories:
print(f"{prefix}{directory}/")
print_directory(os.path.join(path, directory), prefix + '--')
# Then print files
for file in files:
print(f"{prefix}- {file}")
# Change '/path/to/your/wails/app' to the path of your Wails app directory
print_directory('/path/to/your/wails/app')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment