View Full Version : Python TarFile.add question
October 9th, 2009, 01:00 PM
Does anyone know the format that the exclude function takes in the Python TarFile.add as shown:
TarFile.add(name, arcname=None, recursive=True, exclude=None)
The documentation says that it must be a function or parameter, but I've not found anything that works.
I'm using Python 2.6
October 9th, 2009, 01:59 PM
This creates test.tar out of a directory called testdir. It excludes all files in testdir that end with '~'.
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).
October 10th, 2009, 10:11 AM
Much appreciated - thank you very much.
October 10th, 2009, 11:25 AM
That works really well. I can even add extra filters with something like :
return filename.endswith('~') or filename.endswith('mp3').
Any ideas how to exclude whole directories, rather than filter all files based on their extension ?
October 10th, 2009, 12:33 PM
If you put a print statement in exclude_tilde
you'll see that a long path name is passed to the variable filename.
Directories as well as files are passed to exclude_tilde.
So you could filter out a directory like this:
return (('/baddir' in filename) or
October 10th, 2009, 01:08 PM
Absolutely brilliant - thanks heaps.
I was looking at something along the lines of
for filename in os.listdir('/dirx'):
but that was not getting me anywhere. Your suggestion is really very straightforward.
I'm writing my own file backup program and at the same time learning a little about python. I know there is code already out there, but I'm learning by doing.
Again, much appreciated for the help.
Powered by vBulletin® Version 4.2.2 Copyright © 2014 vBulletin Solutions, Inc. All rights reserved.