[英]Export pandas data frame to Azure Data Lake Storage as a CSV file?
[英]Read CSV from Azure Data Lake Storage Gen 2 to Pandas Dataframe | NO DATABRICKS
在过去的 3 个小时里,我一直在尝试将 CSV 从 Azure Data Lake Storage Gen2 (ADLS Gen2) 读取到 pandas 数据帧中。 这在 Azure Blob 存储 (ABS) 中非常容易,但我不知道如何在 ADLS Gen2 中执行此操作。
到目前为止,我已经开发了以下功能:
def read_csv_from_adls_to_df(storage_account_name, storage_account_key, container_name, directory_name, file_name):
service_client = DataLakeServiceClient(account_url=f"https://{storage_account_name}.dfs.core.windows.net", credential=storage_account_key)
file_system_client = service_client.get_file_system_client(file_system = container_name)
directory_client = file_system_client.get_directory_client(directory_name)
file_client = directory_client.create_file(file_name)
file_download = file_client.download_file()
return None
在 file_download 步骤之后,我无法弄清楚我应该做什么。 我尝试了几种方法,例如 readall()、readinto(),但似乎没有任何效果。
以下是我一直用于将 CSV 从 ABS 读取到数据帧中的函数:
def read_csv_from_blob(blob_service_client, container_name, blob_name):
blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
# Retrieve extract blob file
blob_download = blob_client.download_blob()
# Read blob file into DataFrame
blob_data = io.StringIO(blob_download.content_as_text())
df = pd.read_csv(blob_data)
return df
PS:我不是在数据块上这样做。 我在 Python 上这样做。
这不是正确的做法。
适用于 Azure DataLake Gen 2 的 Python SDK 不允许直接读取文件,您需要先将文件下载到本地计算机,然后使用 Pandas 读取。
使用帐户密钥连接到 Azure DataLake
def initialize_storage_account(storage_account_name, storage_account_key):
try:
global service_client
service_client = DataLakeServiceClient(account_url="{}://{}.dfs.core.windows.net".format(
"https", storage_account_name), credential=storage_account_key)
except Exception as e:
print(e)
从目录下载
打开本地文件进行写入。 然后,创建一个代表您要下载的文件的 DataLakeFileClient 实例。 参考下面的例子
def download_file_from_directory():
try:
file_system_client = service_client.get_file_system_client(file_system="my-file-system")
directory_client = file_system_client.get_directory_client("my-directory")
local_file = open("C:\\file-to-download.csv",'wb')
file_client = directory_client.get_file_client("uploaded-file.csv")
download = file_client.download_file()
downloaded_bytes = download.readall()
local_file.write(downloaded_bytes)
local_file.close()
except Exception as e:
print(e)
一旦文件内容存储在本地文件中,您就可以使用 Pandas 读取该文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.