Shashtra shashtra
Shashtra shashtra

Reputation: 1

How to include directory while compressing a tar.gz file in python?

Here's what i'm trying to do :

import tarfile

path = os.path.join(archive_path,"package.tar.gz")
tar_package = tarfile.open(path, "w:gz")
os.chdir(os.path.join(archive_path, "package"))
for name in os.listdir("."):
    tar_package.add(name)
tar_package.close()

This is untaring the file directly to its file contents. Like this:

#untaring tar file
tar -xf package.tar.gz

(directly files from package/ in the location specified.)

I want to untar the file to its directory name with the file contents inside it. Like this:

#untaring tar file
tar -xf package.tar.gz

package/(files inside package in this location)

This is my first time using tarfile in python. If it helps - I'm use python 3.6. Any help is appreciated.

Upvotes: 0

Views: 181

Answers (1)

jdaz
jdaz

Reputation: 6043

tarfile.add supports directories, so you can add "package" directly rather than looping through its contents, and you'll get the result you're looking for:

import tarfile
import os

path = os.path.join(archive_path,"package.tar.gz")
tar_package = tarfile.open(path, "w:gz")
os.chdir(archive_path)
tar_package.add("package")
tar_package.close()

You can specify a different directory name as the second argument to add:

tar_package.add("package", "custom dir name")

You can also specify subdirectories for individual files:

for name in os.listdir("."):
    tar_package.add(name, os.path.join("custom subdir", name))

Upvotes: 1

Related Questions