Example of using Tarfile to compress and extract the tar archive in Python _python

Source: Internet
Author: User
Tags bz2 compress archive python script in python

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

Related Article

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.