zoukankan      html  css  js  c++  java
  • python之解压缩操作

    代码进行解压和压缩

    代码如下:

    #!/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.
     
  • 相关阅读:
    团队项目冲刺第6天
    冲刺阶段第五天
    冲刺阶段前四天总结
    "博客园"用户体验分析
    测试计划
    scrum敏捷开发
    团队开发_软件项目风险管理
    sprint计划会议
    svn 之 svn的两种开发模式
    redis 之 搭建真实集群
  • 原文地址:https://www.cnblogs.com/wanghuixi/p/12116322.html
Copyright © 2011-2022 走看看