How can I create filename.TAR.GZ (ext. In upper case only) using Python tarfile package

188 views Asked by At

I am using the tarfile package for python.

Tar = tarfile.open("filename.tar.gz" mode='w:gz')

NOTE: tarfile.open("filename.**TAR.GZ**" mode='w:gz') is creating two levels of compression. no idea if it is a bug in the package

It is creating "filename.tar.gz"; however, for Unix constraints, we need "filename.**TAR.GZ**"(please note that extension is in uppercase.)

Could you please help me to create filename.TAR.GZ? I can use other packages than tarfile if available for my need.

1

There are 1 answers

2
baduker On

Is this what you want?

import tarfile

file_to_add = "data.csv"
tar_archive = "file.TAR.GZ"

out = tarfile.open(tar_archive, "w:gz")
try:
    print(f"Adding {file_to_add}")
    out.add(file_to_add)
finally:
    print(f"Closing tar archive: {tar_archive}")
    out.close()

print(f"Contents of archive: {tar_archive}")
t = tarfile.open(tar_archive)
for member in t.getmembers():
    print(member.name)

Output

Adding data.csv
Closing tar archive: file.TAR.GZ
Contents of archive: file.TAR.GZ
data.csv

And if I do ls on the working dir, here's what's there:

enter image description here