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?

MrDuk
  • 16,578
  • 18
  • 74
  • 133

1 Answers1

7

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()
Community
  • 1
  • 1
user357269
  • 1,835
  • 14
  • 40
  • I experienced that this code was not excluding dirA, when I tried it with a similar folder structure – charmd Sep 07 '22 at 09:51