-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract_pack.py
52 lines (41 loc) · 1.45 KB
/
extract_pack.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
from shutil import unpack_archive, register_unpack_format
import os
import fnmatch
from py7zr import unpack_7zarchive
import rarfile
register_unpack_format('7zip', ['.7z'], unpack_7zarchive)
# need unrar program
def unpack_rar(archive, path, extra=None):
arc = rarfile.RarFile(archive)
arc.extractall(path)
register_unpack_format('RAR', ['.rar'], unpack_rar)
def extract(compressed_file, path_to_extract):
base_name = os.path.splitext(os.path.basename(compressed_file))[0]
exdir = os.path.join(path_to_extract, base_name)
os.makedirs(exdir, exist_ok=True)
unpack_archive(compressed_file, exdir)
def recursive_unpack(dir_path):
"""
- recursively unpack compressed file in dir_path
- delete compressed file after decompressed
"""
exten = ['7z', 'zip', 'rar']
one_more = False
for r, d, files in os.walk(dir_path):
packed = []
for ext in exten:
code_files = fnmatch.filter(files, '*.' + ext)
if len(code_files) > 0:
tmp_paths = [os.path.join(os.path.abspath(r), f) for f in code_files]
packed.extend(tmp_paths)
if not one_more and len(packed) > 0:
one_more = True
if len(packed) > 0:
print("unpack list:", packed)
for p in packed:
extract(p, os.path.dirname(p))
os.remove(p)
if one_more:
recursive_unpack(dir_path)
if __name__ == '__main__':
recursive_unpack('input')