Python's Tarfile module makes it easy to read tar archive files, and Cow B is able to handle compressed archive files using gzip and bz2 tar.gz and tar.bz2. 
Corresponding to the Tarfile is the ZipFile module, ZipFile is the processing of zip compression. Note: Os.system (cmd) allows the Python script to execute commands, of course including: Tar-czf *.tar.gz *,tar-xzf *.tar.gz,unzip and so on, when I think this can solve the problem, but I feel very amateur. 
 
Using Tarfile compression
Copy the Code code as follows:
 
Import Tarfile 
 
#创建压缩包名 
tar = Tarfile.open ("/tmp/tartest.tar.gz", "W:gz") 
#创建压缩包 
For Root,dir,files in Os.walk ("/tmp/tartest"): 
For file in Files: 
FullPath = Os.path.join (root,file) 
Tar.add (FullPath) 
Tar.close () 
 
 
 
Unzip with Tarfile 
 
Copy CodeThe code is as follows: 
 
def extract (Tar_path, Target_path): 
Try 
tar = Tarfile.open (Tar_path, "R:gz") 
File_names = Tar.getnames () 
For file_name in File_names: 
Tar.extract (file_name, Target_path) 
Tar.close () 
Except Exception, E: 
Raise Exception, E 
 
 
 
The prototype of Open is:
Copy the Code code as follows:
 
Tarfile.open (Name=none, mode= ' R ', Fileobj=none, bufsize=10240, **kwargs) 
 
 
The values of mode are: 
 
Copy CodeThe code is as follows: 
 
' R ' or ' r:* ' Open for reading with transparent compression (recommended). 
' R: ' Open for reading exclusively without compression. 
' R:gz ' Open for reading with gzip compression. 
' r:bz2 ' Open for reading with bzip2 compression. 
' A ' or ' A: ' Open for appending with no compression. The file is created if it does not exist. 
' W ' or ' W: ' Open for uncompressed writing. 
' W:gz ' Open for gzip compressed writing. 
' w:bz2 ' Open for bzip2 compressed writing. 
 
 
 
For more information, please refer to: Tarfile-read and write tar archive files