Skip to content

Instantly share code, notes, and snippets.

@bethropolis
Created August 1, 2023 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bethropolis/159f9a0d5f5026b48a2c0fc2a7201eac to your computer and use it in GitHub Desktop.
Save bethropolis/159f9a0d5f5026b48a2c0fc2a7201eac to your computer and use it in GitHub Desktop.
a python script for automatically creating file structure of any directory.
import os
import fnmatch
# Define the root directory
root_dir = os.getcwd()
# Define the output file name
output_file = "directory_structure.txt"
# Define patterns to ignore
ignore_patterns = []
with open(".gitignore", "r") as f:
for line in f:
line = line.strip().rstrip("/")
if line and not line.startswith("#"):
ignore_patterns.append(line)
# Open the output file for writing
with open(output_file, "w") as f:
# Walk through the directory tree
for dirpath, dirnames, filenames in os.walk(root_dir):
# Filter out directories that match ignore patterns and start with "."
dirnames[:] = [d for d in dirnames if not any(fnmatch.fnmatch(d, p) for p in ignore_patterns) and not d.startswith(".")]
dirnames.sort()
# Filter out files that match ignore patterns and start with "."
filenames = [f for f in filenames if not any(fnmatch.fnmatch(f, p) for p in ignore_patterns) and not f.startswith(".")]
filenames.sort()
# Calculate the depth of the current directory relative to the root directory
depth = dirpath[len(root_dir):].count(os.sep)
# Calculate the indentation level based on the depth
indent = " " * 4 * depth if depth > 0 else ""
# Write the current directory to the output file
f.write(f"{indent}{os.path.basename(dirpath)}/\n")
# Write the files in the current directory to the output file
for file in filenames:
f.write(f"{indent} {file}\n")
print(f"Directory structure written to {output_file} successfully!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment