Example of using Tarfile to compress and unzip a tar archive file in Python

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

  • 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.