tags:

views:

215

answers:

3

When I invoke add() on a tarfile object with a file path, the file is added to the tarball with directory hiearchy associated .In other words, if I unzip the tarfile the directories in the original dir hiearchy are reproduced.

Is there a way to simply add a plainfile without directory info that untarring the resulting tarball produce a flat list of files?

+2  A: 

You can use tarfile.addfile(), in the TarInfo object which is the first parameter you can specify a name that's different from the file you're adding.

This piece of code should add /path/to/filename to the TAR file but will extract it as myfilename:

tar.addfile(tarfile.TarInfo("myfilename"), file("/path/to/filename"))
Wim
Also, it also works for `tar.add()`! To add whole tree, but with a diferent name, just do: `tar.add('/path/to/dir/to/add/', arcname='newdirname')` and then the tarfile will contain a directory with named 'newdirname', and with all it's contents untouched.
Mandx
A: 

Hi!

I have a small code to compress a list of files like this:

try: tar = tarfile.open(destinationfile, "w:bz2") for f in filelist: tar.add(f, f) os.remove(f) tar.close()

except Exception, e: print "Ocorreu um erro - %s" %e

When the compressed file is created, the directory hierarchy is created in the file. When i extract the file, it creates all the directories... How can i change that? The compressed file must have only the files compressed and not all directories...

Thanks ;)

fchevitarese
A: 

Maybe you can use the "arcname" argument to TarFile.add(name, arcname). It takes an alternate name that the file will have inside the archive.