Reputation: 99
I am writing a backup script which uses tarfile module. I am a beginner in python. Here is part of my script - So I have a list of paths that need to be archived in tar.gz. seeing this post, I came up with following. Now archive gets created but the files with .tmp and .data extension aren't getting omitted. 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)
Upvotes: 4
Views: 5057
Reputation: 140307
you're comparing the extensions vs the full names.
Just use os.path.splitext
and compare the extension:
if os.path.splitext(tarinfo.name)[1] in exclude_files:
shorter: rewrite your add
line with a ternary expression and a 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)
Upvotes: 2