Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2851610
  • 博文数量: 348
  • 博客积分: 2907
  • 博客等级: 中校
  • 技术积分: 2272
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-12 09:16
个人简介

专注 K8S研究

文章分类

全部博文(348)

文章存档

2019年(22)

2018年(57)

2016年(2)

2015年(27)

2014年(33)

2013年(190)

2011年(3)

2010年(14)

分类: Python/Ruby

2013-06-29 23:05:30

Python下使用tarfile模块来实现文件归档压缩与解压

 

部分转自:

 

Tarfile.open(cls, name=None, mode='r', fileobj=None, bufsize=10240, **kwargs) method of __builtin__.type instance

    Open a tar archive for reading, writing or appending. Return

    an appropriate TarFile class.

   

    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

 

 

1.压缩,创建tar.gz

 

#!/usr/bin/env python

 

import os

import tarfile

 

#创建压缩包名

 

tar = tarfile.open("/tmp/tartest.tar.gz","w:gz")

 

#创建压缩包

 

for root,dir,files in os.walk("/tmp/tartest"):

 

 

 

        for file in files:

                fullpath = os.path.join(root,file)

                tar.add(fullpath)

 

tar.close()

 

 

2.解压tar.gz

 

#!/usr/bin/env python

 

import tarfile

 

tar = tarfile.open(“/tmp/tartest.tar.gz”)

names = tar.getnames()

 

for name in names:

       tar.extract(name,path=”/tmp”)

 

tar.close()

 

阅读(2086) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~