sarbjit
sarbjit

Reputation: 3894

python tarfile to ignore directory structure while creating tarball

I am having a direcotry structure as :

D:\testfolder\folder_to_tar:
                |---folder1
                      |--- file1.txt
                |---folder2
                      |--- file2.txt
                |---file3.txt

I want to create a tarball using Python at the same directory level. However, I am observing that in the tarball python is including the parent directory as well i.e. testfolder in my example.

Expected Output :
D:\testfolder:
        |---folder_to_tar.tar
                |---folder_to_tar
                        |--folder1
                            .....

Actual Output :
D:\testfolder:
        |---folder_to_tar.tar
                |---testfolder
                       |---folder_to_tar
                                |--folder1
                                       .....

Code :

import tarfile

tarname = "D:\\testfolder\\folder_to_tar"
tarfile1 = "D:\\testfolder\\folder_to_tar.tar"

tarout = tarfile.open(tarfile1,mode="w")

try:
    tarout.add(tarname,arcname=tarname)     
finally:
    tarout.close()

Can some one please help me on how to achieve it.

Upvotes: 1

Views: 1150

Answers (2)

Beli
Beli

Reputation: 594

Try replacing the tarout.add line with:

tarout.add(tarname,arcname=os.path.basename(tarname))

Note: you also need to import os

Upvotes: 6

Dman2
Dman2

Reputation: 740

Have you tried adding \ at the end of tarname?

Upvotes: 0

Related Questions