zoukankan      html  css  js  c++  java
  • 使用Python管理压缩包

    一、 使用tarfile库读取与创建tar包

    1. 创建tar包
    In [1]: import tarfile
    
    In [2]: with tarfile.open('demo.tar',mode='w') as out:
       ...:     out.add('1.txt')
       ...:     out.add('2.txt')
       ...:     
    2. 读取tar包
    In [1]: import tarfile
    
    In [2]: with tarfile.open('demo.tar') as t:
       ...:     for file in t.getmembers():
       ...:         print(file.name)
       ...:         
    1.txt
    2.txt
    3. 创建压缩包
    In [8]: with tarfile.open('demo.tar.gz',mode='w:gz') as out:
       ...:     out.add('1.txt')
       ...:     out.add('2.txt')
    
    4. 读取压缩包
    In [10]: with tarfile.open('demo.tar.gz',mode='r:gz') as out:
        ...:     for f in out.getmembers():
        ...:         print(f.name)
        ...:                 
    1.txt
    2.txt
    5. 提取单个或者所有文件
    In [14]: with tarfile.open('demo.tar.gz',mode='r:gz') as out:
        ...:     out.extract('1.txt')
        ...:                  
    
    In [15]: with tarfile.open('demo.tar.gz',mode='r:gz') as out:
        ...:     out.extractall()
        ...:          
    

    二、使用zipfile库创建和读取压缩包

    1. 创建zip文件
    In [19]: import zipfile
    
    In [20]: newZip = zipfile.ZipFile('demo.zip','w')
    
    In [21]: newZip.write('1.txt')
    
    In [22]: newZip.write('2.txt')
    
    In [23]: newZip.close()
    
    2. 读取zip文件
    In [24]: newZip = zipfile.ZipFile('demo.zip')
    
    In [25]: newZip.namelist()
    Out[25]: ['1.txt', '2.txt']
    
    3. 解压zip文件
    In [27]: newZip.extract('1.txt')
    Out[27]: '/tmp/test/1.txt'
    
    In [28]: newZip.extractall()
    

      

    三、 使用shutil管理压缩包

    In [40]: import shutil
    
    In [41]: shutil.make_archive('demo','zip')
    Out[41]: 'demo.zip'
    
    In [42]: shutil.make_archive('demo','gztar')
    Out[42]: 'demo.tar.gz'
    
    In [43]: shutil.unpack_archive('demo.tar.gz')
    
    In [44]: shutil.unpack_archive('demo.zip')
    

      

  • 相关阅读:
    11.29 两百字
    Django:基础知识
    deepdiff:对比文件
    openpyxl:二次封装
    openpyxl:openpyxl的随笔
    web:pykeyboard、pymouse得使用
    Jmeter:如何让线程顺序执行
    Jmeter:如何将上一个线程得变量使用到下一个线程中,将上一个线程变量设置为全局变量
    Jmeter:BeanShell中的vars.put(string,string)
    Jmeter:数据库查询当天的日期
  • 原文地址:https://www.cnblogs.com/zydev/p/9236638.html
Copyright © 2011-2022 走看看