| 478 | |
| 479 | |
| 480 | def extract_archive(from_path, to_path=None, remove_finished=False): |
| 481 | if to_path is None: |
| 482 | to_path = os.path.dirname(from_path) |
| 483 | |
| 484 | if _is_tar(from_path): |
| 485 | with tarfile.open(from_path, 'r') as tar: |
| 486 | tar.extractall(path=to_path) |
| 487 | elif _is_targz(from_path) or _is_tgz(from_path): |
| 488 | with tarfile.open(from_path, 'r:gz') as tar: |
| 489 | tar.extractall(path=to_path) |
| 490 | elif _is_tarxz(from_path): |
| 491 | with tarfile.open(from_path, 'r:xz') as tar: |
| 492 | tar.extractall(path=to_path) |
| 493 | elif _is_gzip(from_path): |
| 494 | to_path = os.path.join( |
| 495 | to_path, |
| 496 | os.path.splitext(os.path.basename(from_path))[0]) |
| 497 | with open(to_path, 'wb') as out_f, gzip.GzipFile(from_path) as zip_f: |
| 498 | out_f.write(zip_f.read()) |
| 499 | elif _is_zip(from_path): |
| 500 | with zipfile.ZipFile(from_path, 'r') as z: |
| 501 | z.extractall(to_path) |
| 502 | else: |
| 503 | raise ValueError(f'Extraction of {from_path} not supported') |
| 504 | |
| 505 | if remove_finished: |
| 506 | os.remove(from_path) |
| 507 | |
| 508 | |
| 509 | def download_and_extract_archive(url, |