Python: using filter in tarfile

I am writing a backup script that uses the tarfile module. I am new to python. Here is part of my script - So I have a list of paths that need to be zipped to tar.gz. after seeing this post i came up with the following. The archive is now created, but files with the .tmp and .data extensions are not skipped. I am using python 3.5

L = [path1, path2, path3, path4, path5]
exclude_files = [".tmp", ".data"]
# print L

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

with tarfile.open("backup.tar.gz", "w:gz") as tar:
     for name in L:
        tar.add(name, filter=filter_function)

      

+3


source to share


1 answer


you are comparing extensions and qualified names.

Just use os.path.splitext

and compare the extension:

 if os.path.splitext(tarinfo.name)[1] in exclude_files:

      



in short: rewrite the line add

with ternary expression and lambda to avoid the helper function:

tar.add(name, filter=lambda tarinfo: None if os.path.splitext(tarinfo.name)[1] in exclude_files else tarinfo)

      

+1


source







All Articles