Python tarfile and excludes

前端 未结 1 1612
旧时难觅i
旧时难觅i 2020-12-11 05:00

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 va

相关标签:
1条回答
  • 2020-12-11 05:27

    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)
    
    0 讨论(0)
提交回复
热议问题