Python tarfile and exclude

This is an excerpt from the Python documentation:

If an exception is thrown, it must be a function that takes a single file name argument and returns a boolean value. Depending on this value, the corresponding file is either excluded (True) or added (False).

I must admit that I have no idea what this means.

Further

Deprecated since version 2.7: the exclude parameter is deprecated, use the filter parameter instead. For maximum portability, the filter should be used as a keyword argument, and not as a positional argument, so that the code will not be affected unless deleted ultimately deleted.

Ok ... and definition for "filter":

If a filter is specified, it must be a function that takes a TarInfo object and returns a modified TarInfo object. If this returns None instead, the TarInfo object will be excluded from the archive.

... back to the square :)

I really need a way to pass in an array (or delimited string: :) that excludes tarfile.add.

I would not mind if you try to explain what these excerpts are from PyDocs.

PS :.

It just occurred to me:

  • Creating an array of source files
  • popping excludes
  • executing tar.add for the individual array elements remaining

But I would like it to be done more culturally.

+4
source share
1 answer

If an exception is thrown, it must be a function that takes a single file name argument and returns a boolean value. Depending on this value, the corresponding file is either excluded (True) or added (False).

For example, if you want to exclude all file names starting with the letter "a", you would do something like ...

def exclude_function(filename): if filename.startswith('a'): return True else: return False mytarfile.add(..., exclude=exclude_function) 

In your case, you need 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 be too worried about the dismissal warning, but if you want to use the new filter parameter, you will 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) 
+11
source

All Articles