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)
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter