【问题标题】:Issues Reading Azure Blob CSV Into Python Pandas DF将 Azure Blob CSV 读入 Python Pandas DF 的问题
【发布时间】:2020-05-25 09:36:52
【问题描述】:

我正在尝试访问存储在 Azure blob 中的 csv,并将其读入我的 python 脚本中的 pandas 数据帧。但是我遇到了导入问题并实际阅读了 csv。我至少能够使用我的 python 脚本看到它存在,它看起来像:

import os, uuid, sys
from io import StringIO
import pandas as pd
from azure.storage.filedatalake import DataLakeServiceClient
from azure.core._match_conditions import MatchConditions
from azure.storage.filedatalake._models import ContentSettings
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, BlobService

try:  
    global service_client
    storage_account_name = 'ACCOUNT_NAME'
    storage_account_key = 'ACCOUNT_KEY'
    storage_connection_string = 'ACCOUNT_STRING'
    storage_container_name = 'CONTAINER_NAME'
    csv_path = '<PATH_TO>/FILE.csv'

    service_client = DataLakeServiceClient(account_url="{}://{}.dfs.core.windows.net".format(
        "https", storage_account_name), credential=storage_account_key)

    file_system_client = service_client.get_file_system_client(file_system=storage_container_name)

    print('GET PATH(S)')
    paths = file_system_client.get_paths(path=csv_path)
    for path in paths:
        print(path.name + '\n')

    blob_service = BlobService(account_name=storage_account_name, account_key=storage_account_key)
    blobstring = blob_service.get_blob_to_text(storage_container_name,csv_path)
    df = pd.read_csv(StringIO(blobstring))

except Exception as e:
    print(e)

finally:
    print('DONE')

问题是我无法将 csv 正确读取到我的 pd df 中。另外,我遇​​到了实际使用 BlobService 的问题,因为每次尝试运行脚本时,都会出现错误:

ImportError: cannot import name 'BlobService' from 'azure.storage.blob'

我的 azure pip freeze 如下所示:

azure-common==1.1.25
azure-core==1.5.0
azure-storage-blob==12.3.1
azure-storage-common==2.1.0
azure-storage-file-datalake==12.0.1

我在这里做错了什么?

【问题讨论】:

  • Blobservice 不是新的 python Azure blob sdk 中的类。它只是在旧的 python 存储 sdk azure-storage 中。如果你使用新的python存储sdk,我们需要BlobClient来获取一个blob。

标签: python pandas azure azure-blob-storage


【解决方案1】:

根据您提供的代码,您使用 BlobService 类从 Azure blob 存储下载文件。该类在 sdk azure.storage 0.20.0 中。但是你安装sdk azure.storage.blob。所以你会得到错误。既然你已经安装了sdkazure.storage.blob,我们可以通过BlobClient类来下载blob。

例如

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
#download csv file from Azure blob
sas_url = "your blob sas url"
blob_client = BlobClient.from_blob_url(sas_url)
downloaded_blo = blob_client.download_blob()

#read csv file
import pandas as pd
df = pd.read_csv(StringIO(downloaded_blob.content_as_text()) )


【讨论】:

    猜你喜欢
    • 2021-05-14
    • 2020-01-19
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2021-08-22
    • 1970-01-01
    • 2021-02-02
    相关资源
    最近更新 更多