Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Created December 20, 2019 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsbueno/f223a008d971bcc04ebebdd8d134754b to your computer and use it in GitHub Desktop.
Save jsbueno/f223a008d971bcc04ebebdd8d134754b to your computer and use it in GitHub Desktop.
Gist to enable filtering out file-name-patterns when creating an Archive (zipfile, tarball) with Python code
# WARNING: this implementation depends on the internal implementation of shutil.makefile as it is up to Python 3.8.0
# it might change without notice to use pathlib internally, and this will break
import shutil
import re
from unittest.mock import patch
def create_archive_with_filter(*args, filter_out_pattern="", **kwargs):
import os
original_listdir = os.listdir
original_walk = os.walk
def new_listdir(path):
results = original_listdir(path)
return [result for result in results if not re.search(filter_out_pattern)]
def new_walk(path):
for current, dirs, files in original_walk(path):
files = [file for file in files if not re.search(filter_out_pattern)]
yield (current, dirs, files)
with patch("os.listdir", new_lisdir), patch("os.walk", new_walk):
shutil.create_archive(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment