Skip to content

download_utils

extract_archive_file(archive_file, dst_folder=None)

Extract archived file to a directory.

Parameters:

Name Type Description Default
archive_file str

Path to a archive file.

required
dst_folder Optional[str]

Directory where content will be extracted. By default, same folder where archive file is.

None
Source code in services/processor/processor/download_utils.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def extract_archive_file(archive_file, dst_folder=None):
    """Extract archived file to a directory.

    Args:
        archive_file (str): Path to a archive file.
        dst_folder (Optional[str]): Directory where content will be extracted.
            By default, same folder where archive file is.

    """
    if not dst_folder:
        dst_folder = os.path.dirname(archive_file)

    os.makedirs(dst_folder, exist_ok=True)

    archive_ext, archive_type = get_archive_ext_and_type(archive_file)

    print(f"Extracting {archive_file} -> {dst_folder}")
    if archive_type is None:
        _, ext = os.path.splitext(archive_file)
        raise ValueError((
            f"Invalid file extension \"{ext}\"."
            f" Expected {', '.join(IMPLEMENTED_ARCHIVE_FORMATS)}"
        ))

    if archive_type == "zip":
        with zipfile.ZipFile(archive_file) as zip_file:
            zip_file.extractall(dst_folder)

    elif archive_type == "tar":
        if archive_ext == ".tar":
            tar_type = "r:"
        elif archive_ext.endswith(".xz"):
            tar_type = "r:xz"
        elif archive_ext.endswith(".gz"):
            tar_type = "r:gz"
        elif archive_ext.endswith(".bz2"):
            tar_type = "r:bz2"
        else:
            tar_type = "r:*"

        with tarfile.open(archive_file, tar_type) as tar_file:
            tar_file.extractall(dst_folder)

get_archive_ext_and_type(archive_file)

Get archive extension and type.

Parameters:

Name Type Description Default
archive_file str

Path to archive file.

required

Returns:

Type Description

Tuple[str, str]: Archive extension and type.

Source code in services/processor/processor/download_utils.py
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
def get_archive_ext_and_type(archive_file):
    """Get archive extension and type.

    Args:
        archive_file (str): Path to archive file.

    Returns:
        Tuple[str, str]: Archive extension and type.
    """

    tmp_name = archive_file.lower()
    if tmp_name.endswith(".zip"):
        return ".zip", "zip"

    for ext in (
        ".tar",
        ".tgz",
        ".tar.gz",
        ".tar.xz",
        ".tar.bz2",
    ):
        if tmp_name.endswith(ext):
            return ext, "tar"

    return None, None