2

I'm looking for a way to compress a tar file in a tar.gz without directory.

Today my code generate a TAR file without directory with "tarfile" library and arcname arguments but when I want to compress this TAR file in TAR.GZ I don't understand how to delete directory.

I have made many tests in the last 3 days.

My code :

Tarname = example.tar
ImageDirectory = C:\...
TarDirectory = C:\..

tar = tarfile.open(Tarname, "w")
tar.add(ImageDirectory,arcname=TarName)
tar.close()

targz = tarfile.open("example.tar.gz", "w:gz")
targz.add(TarDirectory, arcname=TarName)
targz.close()
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
syl3198045
  • 21
  • 1
  • 2
  • I do not understand the question. What are you getting, and what is it that you want to get instead? Note that `arcname` is not referring to the name of the archive, but rather the name of the entry being added in the tar file. Why are you making `example.tar`, and then `example.tar.gz`? That will just make two different files. – Mark Adler Jan 15 '14 at 15:46
  • Hello Mark, I try to group tif and txt files in a TAR file and then compress this one in a tar.gz file. For all files, I don't want to conserve the original directory. Am I understandable ? – syl3198045 Jan 16 '14 at 08:24
  • Finally I want a TARGZ\TAR\TIF directory but my files are not in the same directory that I use to work and I am forced to pass the files directory which stay in my final archives... – syl3198045 Jan 16 '14 at 08:30

2 Answers2

4

For individual file(s):

tar.add(file, arcname=os.path.basename(file))

for each file that you want to add. basename will strip the directory information.

Or, for a recursive directory:

def flatten(tarinfo):
    tarinfo.name = os.path.basename(tarinfo.name)
    return tarinfo

tar = tarfile.open("example.tar.gz", "w:gz")
tar.add("directory", filter=flatten)
tar.close()
Charles
  • 1,153
  • 1
  • 15
  • 27
Mark Adler
  • 101,978
  • 13
  • 118
  • 158
0

Try using the gzip module : Here is an example of how to use it :

import gzip
f_in = open('file.txt', 'rb')
f_out = gzip.open('file.txt.gz', 'wb')
f_out.writelines(f_in)
f_out.close()
f_in.close()