【问题标题】:Extract particular file from zip blob stored in azure container with python using Jupyter notebook使用 Jupyter notebook 从存储在 azure 容器中的 zip blob 中提取特定文件
【发布时间】:2019-03-29 13:32:51
【问题描述】:

我已将 zip 文件作为 azure 容器中的 blob 上传到我的 azure 帐户中。 Zip 文件包含 .csv、.ascii 文件和许多其他格式。 我需要读取特定文件,比如说包含在 zip 文件中的 ascii 文件数据。我在这种情况下使用 python。

如何从这个 zip 文件中读取特定的文件数据而不下载到本地?我只想在内存中处理这个过程。

我也在尝试使用 azure 为 ML 功能提供的 jypyter notebook 我在这种情况下使用 ZipFile python 包。

请求您协助阅读文件

请找到以下代码sn-p。

blob_service=BlockBlobService(account_name=ACCOUNT_NAME,account_key=ACCOUNT_KEY)
blob_list=blob_service.list_blobs(CONTAINER_NAME)

allBlobs = []
for blob in blob_list:
    allBlobs.append(blob.name)
sampleZipFile = allBlobs[0]
print(sampleZipFile) 

【问题讨论】:

    标签: python azure zipfile msdn


    【解决方案1】:

    下面的代码应该可以工作。此示例使用帐户 URL 和密钥组合访问 Azure 容器。

    from azure.storage.blob import BlobServiceClient
    from io import BytesIO
    from zipfile import ZipFile
    
    key = r'my_key'
    
    service = BlobServiceClient(account_url="my_account_url",
                                credential=key
                                )
    
    container_client = service.get_container_client('container_name')
    
    zipfilename = 'myzipfile.zip'
    
    blob_data = container_client.download_blob(zipfilename)
    blob_bytes = blob_data.content_as_bytes()
    inmem = BytesIO(blob_bytes)
    myzip = ZipFile(inmem)
    
    otherfilename = 'mycontainedfile.csv'
    
    filetoread = BytesIO(myzip.read(otherfilename))
    

    现在您所要做的就是将 filetoread 传递给您通常用来读取本地文件的任何方法(例如,pandas.read_csv()

    【讨论】:

    • 另外,要查找存储在容器中的 blob 列表,您可以使用 blobs = list(container_client.list_blobs()) blob_names = [a.name for a in blobs]
    【解决方案2】:

    您可以使用下面的代码来读取 .zip 文件中的文件,而无需在 python 中提取

    import zipfile
    archive = zipfile.ZipFile('images.zip', 'r')
    imgdata = archive.read('img_01.png')
    

    详情可以参考ZipFile文档here

    或者,你可以做这样的事情

    -- 编码:utf-8 --

    """ 创建于 2019 年 4 月 1 日星期一 11:14:56

    @作者:移动器 """

    import zipfile
    
    zfile = zipfile.ZipFile('C:\\LAB\Pyt\sample.zip')
    for finfo in zfile.infolist():
        ifile = zfile.open(finfo)
        line_list = ifile.readlines()
        print(line_list)
    

    这是相同的输出

    希望对你有帮助。

    【讨论】:

    • 感谢您的回答,但您的代码将在本地运行。要求是在不下载(在内存中)的情况下从 Azure blob 获取 zip 文件并将其提取到 python 脚本
    • @pallaviKulkarni - 你能解决这个问题吗?我有点面临同样的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2018-01-09
    • 2013-09-22
    • 2021-10-10
    • 2020-09-05
    • 2012-01-25
    相关资源
    最近更新 更多