• python 归档tarfile,zipfile学习


    一.tarfile

    用法:

    tarfile.open(cls, name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)  返回一个TarFile类实例

    mode:

        'r' or 'r:*' open for reading with transparent compression

        'r:'         open for reading exclusively uncompressed

        'r:gz'       open for reading with gzip compression

        'r:bz2'      open for reading with bzip2 compression

        'a' or 'a:'  open for appending, creating the file if necessary

        'w' or 'w:'  open for writing without compression

        'w:gz'       open for writing with gzip compression

        'w:bz2'      open for writing with bzip2 compression

     

        'r|*'        open a stream of tar blocks with transparent compression

        'r|'         open an uncompressed stream of tar blocks for reading

        'r|gz'       open a gzip compressed stream of tar blocks

        'r|bz2'      open a bzip2 compressed stream of tar blocks

        'w|'         open an uncompressed stream for writing

        'w|gz'       open a gzip compressed stream for writing

        'w|bz2'      open a bzip2 compressed stream for writing

     

    import tarfile

    1. 压缩目录

    tarball = tarfile.open('/tmp/test.tar.bz2','w:bz2')  ##返回TarFile类实例

    tarball.add('/root/tar')  ##实例方法add

    tarball.close()              ##与file一样有close方法

    2.解压缩tarball

    tarfile = tarfile.open('/tmp/test.tar.bz2')

    tarfile.extractall()    ##解压到同级目录

    tarfile.extractall(‘/root’)    ##解压到/root目录下

     

    二.zipfile

    用法:

    zipfile.ZipFile(file,mode,compression=ZIP_STORED,allZip64=False) 返回实例

    1.反归档

    a = zipfile.ZipFIle('a.zip','r')

    a.namelist()  #查看归档包含的文件

    a.extractall() #

    a.close()

    2.归档

    b= zipfile.ZipFile('b.zip','w')

    b.write('a.html') #添加一个文件

    b.write('c.txt')   #添加另一个

    b.namelist()  #查看归档包含的文件

    b.close()

     

  • 相关阅读:
    单例类
    日期类2
    日历类
    日期转换类
    抓取网页内容并截图
    关于计时器与多线程
    让页面上图片不变形
    Thread 调用方法的方式
    语音放大缩小
    阻止Enter键回发到服务端Asp.net
  • 原文地址:https://www.cnblogs.com/cmsd/p/3303078.html
Copyright © 2020-2023  润新知