Example of tar archive file compression and decompression in Python

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.