[Tutor] How to skip a single file when using shutil.make_archive()

Peter Otten __peter__ at web.de
Sat Aug 15 08:20:25 CEST 2015


Anthony Papillion wrote:

> I'm creating an archive of a directory using shutil.make_archive and need
> to skip a single file if it is present in that directory. Is there a way
> to do this or should I be looking to ZipFile to meet this need?

I should not post this, especially on a tutor list, but as you already have 
a fairly robust solution here's an evil hack:

$ cat make_partial_archive.py
#!/usr/bin/env python3
import os
import shutil
from unittest.mock import patch

_os_path_isfile = os.path.isfile


def accept(path):
    if path in ["delta/one.txt", "beta.txt"]:
        print("skipping %r" % path)
        return False
    return _os_path_isfile(path)


if __name__ == "__main__":
    with patch("os.path.isfile", side_effect=accept):
        shutil.make_archive("archive", "zip", "data")
$ tree data
data
├── alpha.txt
├── beta.txt
├── delta
│   ├── one.txt
│   ├── three.txt
│   └── two.txt
└── gamma.txt

1 directory, 6 files
$ python3 make_partial_archive.py 
skipping 'beta.txt'
skipping 'delta/one.txt'
$ unzip archive.zip -d tmp
Archive:  archive.zip
  inflating: tmp/gamma.txt           
  inflating: tmp/alpha.txt           
  inflating: tmp/delta/two.txt       
  inflating: tmp/delta/three.txt     
$ 

Explanation: The script manipulates the make_archive() implementation for 
zip files by temporarily replacing os.path.isfile() with a custom accept() 
function.




More information about the Tutor mailing list