This article mainly introduces the example of using tarfile to compress and decompress the tar archive file in Python. This article provides examples of decompressing and compressing the code directly. if you need it, refer to the example below.
The zipfile module corresponds to the tarfile, and the zipfile process zip compression. Note: OS. system (cmd) allows Python scripts to execute commands, including tar-czf * .tar.gz *, tar-xzf * .tar.gz, and unzip. when I think this can solve the problem, but I think it's very amateur.
Use tarfile compression
The code is as follows:
Import tarfile
# Create a compressed package name
Tar = tarfile. open ("/tmp/tartest.tar.gz", "w: gz ")
# Create a compressed package
For root, dir, files in OS. walk ("/tmp/tartest "):
For file in files:
Fullpath = OS. path. join (root, file)
Tar. add (fullpath)
Tar. close ()
Decompress with tarfile
The 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 t Exception, e:
Raise Exception, e
The prototype of open is:
The code is as follows:
Tarfile. open (name = None, mode = 'R', fileobj = None, bufsize = 10240, ** kwargs)
The mode values include:
The 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, see tarfile-Read and write tar archive files.