Bootstrap FreeKB - Python (Scripting) - TAR archives
Python (Scripting) - TAR archives

Updated:   |  Python (Scripting) articles

The tarfile module can be used to create and update TAR archives. In this example, an empty TAR archive is created.

  • w (write) - to add a single file to the tar archive
  • a (append) - to append additional files to the tar archive
#!/usr/bin/python
import tarfile
tar_archive = tarfile.open("/tmp/my.tar", "w")
tar_archive.close()

 

In this example, my.tar should be 10240 bytes.

~]$ ll /tmp/my.tar
-rw-rw-r--. 1 john.doe users 0 Sep  5 03:55 /tmp/my.tar

 

But will not contain any files in the TAR archive (this command should return no output).

~]$ tar -tf /tmp/my.tar

 

Here is how you can add a few files to the TAR archive.

#!/usr/bin/python
import tarfile
tar_archive = tarfile.open("/tmp/my.tar", "a")
tar_archive.add("/tmp/hello.txt")
tar_archive.add("/tmp/world.txt")
tar_archive.add("/tmp/foo.log")
tar_archive.add("/tmp/bar.log")
tar_archive.close()

 

And now the TAR archive should contain the files.

~]$ tar -tf /tmp/my.tar
tmp/hello.txt
tmp/world.txt
tmp/foo.log
tmp/bar.log

 

Here is how you can create a gzip compressed TAR archive.

#!/usr/bin/python
import tarfile
tar_archive = tarfile.open("/tmp/my.tar.gz", "a:gz")
tar_archive.add("/tmp/hello.txt")
tar_archive.add("/tmp/world.txt")
tar_archive.add("/tmp/foo.log")
tar_archive.add("/tmp/bar.log")
tar_archive.close()

 

df

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 31aec3 in the box below so that we can be sure you are a human.