Scrape .py file structure

PHOTO EMBED

Thu Dec 29 2022 07:24:06 GMT+0000 (Coordinated Universal Time)

Saved by @sfull

import os

def read_py_files(directory):
    result = ""
    seen_dirs = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(".py"):

              # Add directory name to seen_dirs if it's first encounter
              if root.upper().replace(r"./", "") not in seen_dirs:
                result += f'\n\n\n\n\n# {root.upper().replace(r"./", "")}\n\n\n\n\n'
                seen_dirs.append(root.upper().replace(r"./", ""))

              # Add file name followed by file contents
              file_path = os.path.join(root, file)
              with open(file_path, "r") as f:
                    # File name
                    curdir = root.upper().replace(r"./", "")
                    result += f"\n\n\n## {curdir} -- {file}\n\n\n"
                    # File contents
                    result += f.read()
    return result

string_var = read_py_files(".")
print(string_var)
content_copyCOPY