代码改变世界

python 归档tarfile,zipfile学习

2013-09-05 12:59  cmsd  阅读(682)  评论(0编辑  收藏  举报

一.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()