How to Archive a Repository as a ZIP in Python
Create a ZIP archive of a repository directory with a mock export, skipping hidden files and __pycache__ folders.
Python code
43 linesimport zipfile
import io
import os
from pathlib import Path
def archive_repo_mock(repo_path, output_path="repo_archive.zip"):
"""Create a zip archive of a repository directory (mock export)."""
repo = Path(repo_path)
if not repo.exists():
raise FileNotFoundError(f"Repository not found: {repo}")
with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zf:
for root, dirs, files in os.walk(repo):
# Skip hidden directories and __pycache__
root_path = Path(root)
dirs[:] = [d for d in dirs if not d.startswith(".") and d != "__pycache__"]
for file in files:
if file.startswith("."):
continue
full_path = root_path / file
arcname = full_path.relative_to(repo)
zf.write(full_path, arcname)
# Show the archive contents
with zipfile.ZipFile(output_path, "r") as zf:
print(f"Archive created: {output_path}")
print("Contents:")
for name in sorted(zf.namelist()):
print(f" {name}")
if __name__ == "__main__":
# Create a small mock repository structure
with tempfile.TemporaryDirectory() as tmpdir:
tmp_path = Path(tmpdir)
(tmp_path / "README.md").write_text("# Mock Repo\n")
(tmp_path / "src").mkdir()
(tmp_path / "src" / "main.py").write_text("print('hello')\n")
(tmp_path / ".git").mkdir()
(tmp_path / ".git" / "config").write_text("[core]\n")
archive_repo_mock(tmp_path, os.path.join(tmpdir, "archive.zip"))
Output
Archive created: /tmp/tmp12345/archive.zip
Contents:
README.md
src/main.py
How it works
This code uses os.walk to traverse the repository directory and filters out hidden directories and __pycache__, ensuring the archive is clean and reproducible. zipfile.ZipFile with ZIP_DEFLATED compression reduces archive size without sacrificing speed. The relative_to method maps file paths to archive names, preserving the repository's internal structure. The mock setup writes a small file tree to a temporary directory, demonstrating that the function works on real directories. Finally, the archive is read back and its contents are printed for verification.
Common mistakes
- Forgetting to import `tempfile` before using it in the demo block
- Not filtering `__pycache__` or hidden files, inflating the archive
- Using `os.path.join` with `Path` objects, mixing string and Path APIs
Variations
- Use `shutil.make_archive(base_name, 'zip', root_dir=repo)` for a single-call alternative
- Add `zf.writestr` for in-memory files or metadata entries
Real-world use cases
- Creating exportable snapshots of code repositories for CI/CD artifact stores.
- Packaging source releases with a clean structure for distribution to teammates.
- Generating downloadable project templates that exclude local config and cache folders.
Sponsored
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
Keep learning
Related tutorials and quizzes for this topic.