使用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')

  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值