Skip to content Skip to sidebar Skip to footer

Python Tarfile And Excludes

This is an excerpt from Python's documentation: If exclude is given it must be a function that takes one filename argument and returns a boolean value. Depending on this value t

Solution 1:

If exclude is given it must be a function that takes one filename argument and returns a boolean value. Depending on this value the respective file is either excluded (True) or added (False).

For example, if you wanted to exclude all filenames beginning with the letter 'a', you'd do something like...

def exclude_function(filename):
    if filename.startswith('a'):
        return True
    else:
        return False

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

For your case, you'd want something like...

EXCLUDE_FILES = ['README', 'INSTALL', '.cvsignore']

def exclude_function(filename):
    if filename in EXCLUDE_FILES:
        return True
    else:
        return False

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

...which can be reduced to...

EXCLUDE_FILES = ['README', 'INSTALL', '.cvsignore']

mytarfile.add(..., exclude=lambda x: x in EXCLUDE_FILES)

Update

TBH, I wouldn't worry too much about the deprecation warning, but if you want to use the new filter parameter, you'd need something like...

EXCLUDE_FILES = ['README', 'INSTALL', '.cvsignore']

def filter_function(tarinfo):
    if tarinfo.name in EXCLUDE_FILES:
        return None
    else:
        return tarinfo

mytarfile.add(..., filter=filter_function)

...which can be reduced to...

EXCLUDE_FILES = ['README', 'INSTALL', '.cvsignore']

mytarfile.add(..., filter=lambda x: None if x.name in EXCLUDE_FILES else x)

Post a Comment for "Python Tarfile And Excludes"