Skip to content

Instantly share code, notes, and snippets.

@esmitt
Last active April 15, 2025 14:21
Show Gist options
  • Save esmitt/15def78c453113103c363c718aabacf1 to your computer and use it in GitHub Desktop.
Save esmitt/15def78c453113103c363c718aabacf1 to your computer and use it in GitHub Desktop.
Return a single string with the content of all files inside a folder. For each file, it indicates the filename and its content. for now, ignore single-line comments. Very useful to ask to ChatGPT for instance about what is wrong with your code
from pathlib import Path, PurePath
from typing import List, Optional
def stringify_file(filename: str) -> str:
single_file = ""
with open(filename, encoding="utf-8") as file:
for line in file:
stripped = line.strip()
if stripped:
code_part = line.split('#')[0]
single_file += code_part
return single_file
def single_str_for_python_files(
directory: PurePath = Path.cwd(),
exclude_dirs: Optional[List[PurePath]] = None,
exclude_files: Optional[List[Path]] = None
) -> str:
result = ""
base_path = Path(directory).resolve()
exclude_dirs = {base_path / ex_dir for ex_dir in (exclude_dirs or [])}
exclude_files = {Path(f).resolve() for f in (exclude_files or [])}
for filename in base_path.rglob("*.py"):
if filename.name == "__init__.py":
continue
if filename.resolve() in exclude_files:
continue
if any(parent in exclude_dirs for parent in filename.parents):
continue
rel_path = filename.relative_to(base_path)
result += f"\n--{rel_path}--\n"
result += stringify_file(str(filename))
return result
# example usage
if __name__ == "__main__":
current_file = Path(__file__).resolve()
excluded_dirs = [Path(".venv"), Path(".venvironment"), Path("tests")]
excluded_files = [current_file, Path("core/logger.py")]
print(single_str_for_python_files(
Path("."),
exclude_dirs=excluded_dirs,
exclude_files=excluded_files
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment