Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can files be added to a tarfile with Python, without adding the directory hierarchy?

Tags:

python

tar

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 adding a plain file without directory info that untarring the resulting tarball produce a flat list of files?

like image 519
theactiveactor Avatar asked Feb 10 '10 19:02

theactiveactor


People also ask

How do I tar multiple files in Python?

Use the tarfile module to create a zip archive of a directory. Walk the directory tree using os. walk and add all the files in it recursively.

How do I open a Tarfile file in Python?

You can use the tarfile module to read and write tar files. To extract a tar file, you need to first open the file and then use the extract method of the tarfile module.

How do I read a TGZ file in Python?

In order to extract or un-compress “. tar. gz” files using python, we have to use the tarfile module in python. This module can read and write .


1 Answers

Using the arcname argument of TarFile.add() method is an alternate and convenient way to match your destination.

Example: you want to archive a dir repo/a.git/ to a tar.gz file, but you rather want the tree root in the archive begins by a.git/ but not repo/a.git/, you can do like followings:

archive = tarfile.open("a.git.tar.gz", "w|gz") archive.add("repo/a.git", arcname="a.git") archive.close() 
like image 188
diabloneo Avatar answered Sep 27 '22 22:09

diabloneo