Python's self-contained tarfile module makes it easy to read the tar archive, and cow B can handle using GZIP and bz2 to compress archive files tar.gz and tar.bz2.
Corresponding to the Tarfile is the ZipFile module, ZipFile is the processing of zip compression. Please note: os.system (cmd) can make the Python script execute commands, including: Tar-czf *.tar.gz *,tar-xzf *.tar.gz,unzip, etc., when I feel that this can solve the problem, but I feel very amateur.
Using Tarfile compression
Copy 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 ()
using Tarfile decompression
Copy Code code 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
Where the Open prototype is:
Copy Code code as follows:
Tarfile.open (Name=none, mode= ' R ', Fileobj=none, bufsize=10240, **kwargs)
The values of mode are:
Copy Code code 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.
More please refer to: Tarfile-read and write tar archive files