-
Notifications
You must be signed in to change notification settings - Fork 12.5k
/
Copy pathtar.py
67 lines (60 loc) · 2.14 KB
/
tar.py
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
import gzip
import os
import tarfile , zipfile, rarfile
from library.utils.file import get_filetype
from library.utils.path import make_dir
from library.utils.type_conv import random_str
def uncompress(src_file, dest_dir):
result = get_filetype(src_file)
if not result[0] :
return (False, result[1], '')
filefmt = result[1]
result = make_dir(dest_dir)
if not result :
return (False, '创建解压目录失败', filefmt)
if filefmt in ('tgz', 'tar') :
try :
tar = tarfile.open(src_file)
names = tar.getnames()
for name in names:
tar.extract(name, dest_dir)
tar.close()
except Exception as e :
return (False, e, filefmt)
elif filefmt == 'zip':
try :
zip_file = zipfile.ZipFile(src_file)
for names in zip_file.namelist():
zip_file.extract(names, dest_dir)
zip_file.close()
except Exception as e :
return (False, e, filefmt)
elif filefmt == 'rar' :
try :
rar = rarfile.RarFile(src_file)
os.chdir(dest_dir)
rar.extractall()
rar.close()
except Exception as e :
return (False, e, filefmt)
elif filefmt == 'gz' :
try :
f_name = dest_dir + '/' + os.path.basename(src_file)
# 获取文件的名称,去掉
g_file = gzip.GzipFile(src_file)
# 创建gzip对象
open(f_name, "w+").write(g_file.read())
# gzip对象用read()打开后,写入open()建立的文件中。
g_file.close()
# 关闭gzip对象
result = get_filetype(src_file)
if not result[0] :
new_filefmt = '未知'
else :
new_filefmt = result[1]
return (True, '解压后的文件格式为:' + new_filefmt, filefmt)
except Exception as e :
return (False, e, filefmt)
else :
return (False, '文件格式不支持或者不是压缩文件', filefmt)
return (True, '', filefmt)