【问题标题】:How to QUICKLY download Tar file, untar it and upload the content to Azure Block storage using Python?如何使用 Python 快速下载 Tar 文件、解压缩并将内容上传到 Azure 块存储?
【发布时间】:2021-04-14 06:15:12
【问题描述】:

我有以下在 Jupyter Notebook 中运行的 Python 代码。它从源位置下载 tar 文件,解压缩并上传到 Azure Blob 存储。

import os
import tarfile
from azure.storage.blob import BlobClient

def upload_folder(local_path):
    connection_string = "XXX"
    container_name = "mycontainername"
    
    with tarfile.open(local_path, "r") as file:
        for each in file.getnames():
            print(each)
            file.extract(each)          
            blob = BlobClient.from_connection_string(connection_string,
                                                     container_name=container_name,
                                                     blob_name=each)

            with open(each, "rb") as f:
                blob.upload_blob(f, overwrite=True)
            os.remove(each)


# MAIN
!wget https://path/to/myarchive.tar.gz

local_path = "myarchive.tar.gz"

upload_folder(local_path)

!rm -rf myarchive.tar.gz
!rm -rf myarchive

myarchive.tar.gz 占用 1Gb,相当于大约 4Gb 的未压缩数据。 问题是即使对于相对较小的数据量,运行此代码也需要很长时间。大约需要 5-6 小时。

我做错了什么?有什么方法可以优化我的代码以更快地运行它?

【问题讨论】:

  • 看起来您正在从 tar 中单独提取每个文件,然后从下一个文件重新开始。那不会有效率。必须有一种方法可以一次通过,但我不熟悉tarfile,所以我无法回答。

标签: python azure azure-blob-storage azure-sdk


【解决方案1】:

您可以将上传文件处理作为一项任务,并使用multiprocessing 创建一些进程池。然后我们可以在池中一次性运行一些任务来增加脚本的速度。更多详情请参考herehere

【讨论】:

    猜你喜欢
    • 2012-03-22
    • 2019-06-14
    • 2020-12-16
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2013-02-27
    相关资源
    最近更新 更多