Azure数据湖-使用Python读取

问题描述 投票:0回答:1

我正在尝试在Databricks笔记本中使用Python从Azure数据湖中读取文件。这是我使用的代码,

from azure.storage.filedatalake import DataLakeFileClient

file = DataLakeFileClient.from_connection_string("DefaultEndpointsProtocol=https;AccountName=mydatalake;AccountKey=******;EndpointSuffix=core.windows.net",file_system_name="files", file_path="/2020/50002")

with open("./sample.txt", "wb") as my_file:
    download = file.download_file()
    content = download.readinto(my_file)
    print(content)

我得到的输出为0。您能指出我做错了什么吗?我的期望是打印文件内容。

python azure azure-data-lake azure-databricks
1个回答
0
投票

from_connection_string方法返回一个DataLakeFileClient,您不能用它来下载文件。

如果要下载文件到本地,可以参考下面的代码。

import os, uuid, sys
from azure.storage.filedatalake import DataLakeServiceClient

service_client = DataLakeServiceClient.from_connection_string("DefaultEndpointsProtocol=https;AccountName=***;AccountKey=*****;EndpointSuffix=core.windows.net")

file_system_client = service_client.get_file_system_client(file_system="test")

directory_client = file_system_client.get_directory_client("testdirectory")

file_client = directory_client.get_file_client("test.txt")

download=file_client.download_file()

downloaded_bytes = download.readall()

with open("./sample.txt", "wb") as my_file:
    my_file.write(downloaded_bytes)
    my_file.close()

如果需要更多示例代码,可以参考此文档:Azure Data Lake Storage Gen2

© www.soinside.com 2019 - 2024. All rights reserved.