Skip to content

Instantly share code, notes, and snippets.

@adbac
Created February 23, 2025 22:15
Show Gist options
  • Select an option

  • Save adbac/7189b81ca0a5f07668bced56068d2d6d to your computer and use it in GitHub Desktop.

Select an option

Save adbac/7189b81ca0a5f07668bced56068d2d6d to your computer and use it in GitHub Desktop.
Python script to zip a folder without macOS metadata like .DS_Store files (and the _MACOSX folder, normally).
import os
import zipfile
from pathlib import Path
def zipFolder(zipDir, sourcePath, excludePatterns=[]):
"""
Zips a folder and its contents, without macOS metadata like `.DS_Store` files.
*zipDir* is the path to the directory to put the zip file in,
*sourcePath* is the path to the folder to zip.
"""
sourcePath = Path(sourcePath)
zipDir = Path(zipDir)
zipPath = zipDir / f"{sourcePath.name}.zip"
if zipPath.exists():
os.remove(zipPath)
excludePatterns = ["*/.DS_Store"] + excludePatterns
with zipfile.ZipFile(zipPath, "w", zipfile.ZIP_DEFLATED) as zipf:
for filePath in sourcePath.rglob("*"):
if filePath.is_file() and not any(filePath.match(pattern) for pattern in excludePatterns):
zipf.write(filePath, filePath.relative_to(sourcePath))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment