Creating archive with shutil.make_archive() while excluding some path(s)
Asked Answered
T

1

12

Is there a way to have shutil.make_archive exclude some child directories, or alternatively, is there a way to append directories to a single archive through shutil?

Examples are fun:

/root
  /workingDir
      /dir1
      /dir2
          /dirA
          /dirB
      /dir3   

Suppose I wanted to create an archive from within workingDir that included everything except for dirA -- how could I do this? Is it possible without writing a method to loop through the entire tree?

Tjirebon answered 10/8, 2016 at 21:9 Comment(0)
B
8

I don't think this is possible with directly with shutil. It is possible to do it with tarfile (which is used by shutil internally anyway)

Tarfile.add has a filter argument that you can use precisely for this purpose.

See also this answer: Python tarfile and excludes

EXCLUDE_FILES = ['dir2/dirA']
tar = tarfile.open("sample.tar.gz", "w:gz")
tar.add("workingDir", filter=lambda x: None if x.name in EXCLUDE_FILES else x)
tar.close()
Banjermasin answered 10/8, 2016 at 21:17 Comment(1)
I experienced that this code was not excluding dirA, when I tried it with a similar folder structureOslo

© 2022 - 2024 — McMap. All rights reserved.