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

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

    0、先创建一些测试文件

    touch {1..2}.txt

    1、创建压缩包

    In [7]: import tarfile 
    In [9]: with tarfile.open('demo.tar',mode='w') as out: 
       ...:     out.add('1.txt') 
       ...:     out.add('2.txt') 
       ...:                                                                                                                                                                 
    ---------------------------------------------------------------------------
    FileNotFoundError                         Traceback (most recent call last)
    <ipython-input-9-0c341d269b4b> in <module>
          1 with tarfile.open('demo.tar',mode='w') as out:
    ----> 2     out.add('1.txt')
          3     out.add('2.txt')
          4 
    # 最后一空行直接回车即可

    2、读取tar包

    In [3]: with tarfile.open(‘demo.tar’) as t:
    …: for file in t.getmembers():

    …: print(file.name)

    …:

    1.txt

    2.txt

    3、创建压缩包

    with tarfile.open(‘demo.tar.gz’,mode=’w:gz’) as out:
    …: out.add(‘1.txt’)

    …: out.add(‘2.txt’)

    …:

    4、读取压缩包

    In [6]: 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]: ls

    1.txt anaconda-ks.cfg demo.tar demo.tar.gz

    In [16]: with tarfile.open(‘demo.tar.gz’,mode=’r:gz’) as out:

    …: out.extractall()

    …:

    In [17]: ls

    1.txt 2.txt anaconda-ks.cfg demo.tar demo.tar.gz

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

    1、创建zip文件

    In [1]: import zipfile
    In [2]: newZip = zipfile.ZipFile(‘demo.zip’,’w’)

    In [3]: newZip.write(‘1.txt’)

    In [4]: newZip.write(‘2.txt’)

    In [5]: newZip.close()

    In [6]: ls

    1.txt 2.txt anaconda-ks.cfg demo.tar demo.tar.gz demo.zip

    2、读取zip文件

    In [7]: newZip = zipfile.ZipFile(‘demo.zip’)
    In [8]: newZip.namelist()

    Out[8]: [‘1.txt’, ‘2.txt’]

    3、解压zip文件

    In [12]: newZip.extract(‘1.txt’)
    Out[12]: ‘/root/1.txt’

    In [13]: newZip.extractall()

    In [14]: ls

    1.txt 2.txt anaconda-ks.cfg demo.tar demo.tar.gz demo.zip

    三、使用shutil管理压缩包

    In [1]: import shutil
    In [2]: shutil.make_archive(‘demo’,’zip’)

    Out[2]: ‘demo.zip’

    In [3]: shutil.make_archive(‘demo’,’gztar’)

    Out[3]: ‘demo.tar.gz’

    In [4]: shutil.unpack_archive(‘demo.tar.gz’)

    In [5]: shutil.unpack_archive(‘demo.zip’)

  • 相关阅读:
    关于windows线程的各种状态
    《深入理解计算机系统》(第二版)第二章练习题3
    《深入理解计算机系统》(第二版)第二章中的一练习题2
    Linux进程/线程模型
    用户进程中执行的操作系统
    关于操作系统模型
    《深入理解计算机系统》(第二版)第二章中的一题目
    并发问题互斥(Dekker算法和Peterson算法)
    概率问题:星期二出生的孩子
    Yii添加扩展加载Ckeditor 4.0以上版本
  • 原文地址:https://www.cnblogs.com/liujunjun/p/13475463.html
Copyright © 2011-2022 走看看