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