-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathextract.py
48 lines (43 loc) · 1.37 KB
/
extract.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
# ______________________________________________________________________________
#
# reJARchiver - extract.py
#
# Recursively extracts various archive types.
# ______________________________________________________________________________
#
import os, sys, shutil
from zipfile import ZipFile
from unrar.rarfile import RarFile
def extract(path: str):
"""Extracts a ZIP/7Z/RAR archive to a subdirectory."""
try:
extpath = path + '_ext/'
if path.endswith('.zip'):
with ZipFile(path) as zip:
zip.extractall(extpath)
elif path.endswith('.7z'):
# py7zr fails on archives containing illegal filenames, so we use the CLI tool
# On Linux, install it with package manager, on Windows an exe is provided
os.system(f"7za x -y -o{extpath} {path}")
elif path.endswith('.rar'):
with RarFile(path) as rar:
rar.extractall(extpath)
return extpath
except:
print(f"Failed to extract {path}")
shutil.rmtree(extpath, True)
return None
def recursive_extract(path: str):
if path is None: return
for dir in os.walk(path):
[dirname, folders, files] = dir
for file in files:
if file.endswith(('.zip', '.7z', '.rar')):
filepath = os.path.join(dirname, file)
print(f"extracting {filepath}")
recursive_extract(extract(filepath))
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: extract.py <directory>")
sys.exit()
recursive_extract(sys.argv[1])