代码进行解压和压缩

代码如下:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import os
import tarfile
class software(object):

    def __init__(self):
        super(software, self).__init__()


    def start(self):
        # self.file_compression()
        #
        # self.file_uncompression()
        self.file()

    #解压
    def file_uncompression(self):
        tar = tarfile.open("123.tar.gz")
        tar.extractall("/opt/") # 解压到的路径
        tar.close()

    # 将路径中的文件  压缩
    def file_compression(self):
        cwd = os.getcwd() #  获取当前路径
        print "cwd:",cwd
        tar = tarfile.open('test.tar', 'w:gz')
        # 把当前所有的文件 都压缩
        for root, dir, files in os.walk(cwd):
            for file in files:
                print "file:", file
                fullpath = os.path.join(root, file)
                print "fullpath:", fullpath
                tar.add(fullpath)

    #有选择的解压缩
    # def file(self):
    #     tar = tarfile.open("123.tar.gz")
    #     tar.extractall(members=self.py_files(tar))
    #     tar.close()
    # def py_files(members):
    #     for tarinfo in members:
    #         if os.path.splitext(tarinfo.name)[1] == ".py":
    #             yield tarinfo


if __name__ == '__main__':
    print("main")
    s = software()
    s.start()

函数介绍:

tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)

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