【问题标题】:How do you delete a file from an Azure Data Lake using the Python SDK?如何使用 Python SDK 从 Azure 数据湖中删除文件?
【发布时间】:2020-12-08 00:44:40
【问题描述】:

我正在使用适用于 Python 3.8 的 azure-storage-file-datalake 插件。 SDK 在这里进行了深入的描述—— https://docs.microsoft.com/en-us/python/api/azure-storage-file-datalake/azure.storage.filedatalake.datalakedirectoryclient?view=azure-python,但是在哪里没有关于是否可以从数据湖中删除文件的描述,SDK仅描述了删除目录。可以删除文件吗?

编辑:响应给出的答案,我尝试了这个......

file = DataLakeFileClient.from_connection_string(
                my_connection_string, 
                file_system_name=filesystem, 
                file_path=path
            )
            file.delete_file()

但最后一行导致此错误

TypeError('element indices must be integers')

【问题讨论】:

  • 你好,我想看看你是否解决了这个问题。如果解决了,您能接受下面的答案吗?如果您还有更多问题,请告诉我:)。谢谢。

标签: python-3.x azure azure-data-lake data-lake


【解决方案1】:

更新:

首先,我正在为 adls gen2 安装最新的 python sdk。使用以下命令:

pip install azure-storage-file-datalake==12.1.1

这是我的测试代码:

from azure.storage.filedatalake import DataLakeFileClient

conn_str="xxxx"
filesystem="aaa"
file_path="foo2.txt" #if the file is in a directory, like in directory test1, you should specify the path as "test1/foo2.txt"

fileClient = DataLakeFileClient.from_connection_string(
    conn_str=conn_str,
    file_system_name=filesystem,
    file_path=file_path
)

fileClient.delete_file()

print("**completed**")

以及测试结果:


原答案:

如果你想删除一个文件,你应该看看DataLakeFileClient class。在这个类中,它有一个delete_file 方法。请查看this article的用法。

或者当你使用DataLakeDirectoryClient class时,可以通过DataLakeDirectoryClient实例的get_file_client()方法获取文件客户端,然后调用delete_file()方法。

如果您还有其他问题,请告诉我。

【讨论】:

  • 嗨,我试了一下,但它导致了一个神秘的“TypeError('元素索引必须是整数')”错误。我将代码作为对我的问题的编辑。
  • @Dave 确认一下,您使用的是 Azure Data Lake Gen2 吗?
  • 嗨,是的。如果重要的话,插件版本也是 12.0.2。
  • @Dave,版本是 12.0.2 还是 12.1.1 都没有关系。请尝试代码,并让我知道任何问题:)
  • 嗨,谢谢。 “delete_file”调用引发异常“azure.core.exceptions.HttpResponseError:操作返回无效状态'已接受'”但是当我检查数据湖时,文件已被删除,所以我猜它有效吗? Idk,我觉得应该有一个更干净的解决方案,它根本不会抛出异常并且仍然​​会删除文件。但是我对这个 SDK 不是很熟悉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 2021-04-13
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多