Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 367
MrDuk Avatar asked Aug 10 '16 21:08

MrDuk


1 Answers

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()
like image 154
user357269 Avatar answered Oct 19 '22 23:10

user357269