使用 Python3 解压 gz、tar、tgz、zip、rar 五种格式的压缩文件例子 - lykops - 博客园

gz: 即 gzip,通常只能压缩一个文件;与 tar 结合起来就可以实现先打包,再压缩。

tar: linux 系统下的打包工具,只打包,不压缩。

tgz:即 tar.gz,先用 tar 打包,然后再用 gz 压缩得到的文件。

zip: 不同于 gzip,虽然使用相似的算法,可以打包压缩多个文件,不过分别压缩文件,压缩率低于 tar。

rar:打包压缩文件,最初用于 DOS,基于 window 操作系统。压缩率比 zip 高,但速度慢,随机访问的速度也慢。

# Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import gzip
import os
import tarfile
import zipfile
import rarfile


def get_filetype(filepath):
extension = filepath.split('.')[-2:]
if extension[0] == 'tar' and extension[1] == 'gz':
return 'tgz'
return extension[1]


def uncompress(compress_file, dest_dir):
extension = get_filetype(compress_file)

try:
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)
except Exception as a:
return (False, 'Create Uncompressed Dir Failed', extension)

if extension in ('tgz', 'tar'):
try:
tar = tarfile.open(compress_file)
names = tar.getnames()
for name in names:
tar.extract(name, dest_dir)
tar.close()
except Exception as e:
return (False, e, extension)

elif extension == 'zip':

try:
extension = zipfile.ZipFile(compress_file)
for name in extension.namelist():
extension.extract(name, dest_dir)
extension.close()
except Exception as e:
return (False, e, extension)

elif extension == 'rar':

try:
rar = rarfile.RarFile(compress_file)
os.chdir(dest_dir)
rar.extractall()
rar.close()
except Exception as e:
return (False, e, extension)

elif extension == 'gz':
try:
# gz just compress one file, generally use tar package file then use gz compress
# test.txt.gz => test.txt
file_name = dest_dir + '/' + \
os.path.splitext(os.path.basename(compress_file))[0]

with gzip.open(compress_file, 'rb') as gz, open(file_name, 'wb') as f:
f.write(gz.read())

except Exception as e:
return (False, e, extension)
else:
return (False, 'Unsupported Compressed File Type', extension)

return (True, '', extension)


uncompress('git.txt.gz', 'gz')
Edited on