When I invoke add()
on a tarfile
object with a file path, the file is added to the tarball with directory hierarchy associated. In other words, if I unzip the tarfile the directories in the original directories hierarchy are reproduced.
Is there a way to simply add a plain file, without directory info, so that untarring the resulting tarball produces a flat list of files?
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.txt"), open("/path/to/filename.txt"))