0

I can use gzip to compress a single file, but I can not use it to compress a folder. I used this:

tar = tarfile.open("TarName.tar.gz", "w:gz")
tar.add("folder/location", arcname="TarName")
tar.close()

The folder was compressed, how can I uncompress it? Or is there any other methods to compress a folder? By the way, please add the way to uncompress. Thanks very much

thiiiiiking
  • 1,233
  • 3
  • 12
  • 16

2 Answers2

1

You just need to open the tarfile and extract:

import tarfile

with tarfile.open("TarName.tar.gz") as tar:    
    tar.extractall()

Everything you need to know is provided in the extensive examples in the documentation. If you are worried about external files you can take one of the approaches from this question

Community
  • 1
  • 1
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • thanks very much, I get the right answer from your code. – thiiiiiking Dec 12 '15 at 12:28
  • [``extractall`` is dangerous](https://docs.python.org/2/library/tarfile.html#tarfile.TarFile.extractall) and should *not* be used with untrusted input. – Jonas Schäfer Dec 12 '15 at 12:28
  • @JonasWielicki, if the OP is creating the file what is the issue? They asked for a way to uncompress which is what extractall is doing and what is used in the documentation examples – Padraic Cunningham Dec 12 '15 at 12:31
  • @PadraicCunningham I thought I’d mention it in case someone looks at this question in the future who did not create the files. Also we do not know how the OP is processing the files, e.g. whether they are transmitted automatically over untrusted paths or anything like that. – Jonas Schäfer Dec 12 '15 at 12:37
0

Conversely, you can use tarfile library to open tar.gz archives. For that, you can use the mode r:gz.

Python documentation has a section about data compression and archiving that you might like: https://docs.python.org/2/library/archiving.html

For folders, zip and tar.gz module are the two available modules in the standard library.

Last, I recommend you to have a look to the capacity of with statements on open/close patterns.

ohe
  • 3,461
  • 3
  • 26
  • 50