使用Python读取Azure数据湖

2024-09-30 16:33:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Databricks笔记本中使用Python从Azure Data lake读取一个文件。 这是我使用的代码

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。你能指出我做错了什么吗。我的期望是打印文件内容


Tags: 文件代码fromdatamydownload笔记本storage
1条回答
网友
1楼 · 发布于 2024-09-30 16:33:28

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

相关问题 更多 >