0

I am trying to tar the contents of a directory using the tarfile module.

Say this directory, called 'A', has several subdirectories, 'a' and 'a1' etc... Is there a way to exclude these directories from the tarfile object when trying to add? For example, I have a list of files to exclude, which I put in the list:

EXCLUDE_FILES = ['README', '.gitignore']

I can exclude these following a solution found here. However, can this method be altered to exclude directories or is there another way in which it can be done?

Community
  • 1
  • 1
domsmiff
  • 57
  • 2
  • 6

1 Answers1

0

Building on the example from the other answer you've posted, can you not do:

def exclude_function(filename):
    return os.path.isdir(filename):

mytarfile.add(..., exclude=exclude_function)

Or to simplify, perhaps:

mytarfile.add(..., exclude=os.path.isdir)

Using filter:

def filter_function(tarinfo):
   if os.path.isdir(tarinfo.name):
        return None
   return tarinfo

mytarfile.add(..., filter=filter_function)
Simon Fraser
  • 2,758
  • 18
  • 25
  • 2
    For reference, version 3.7 has removed support for the `exclude` param. You must use `filter`. https://github.com/python/cpython/commit/4f76fb16b7e00dac91ea4089a28e06e8720e3294 – Punkman Apr 16 '20 at 13:53