如果未找到,则创建文件 system/container

Create file system/container if not found

我正在尝试将 CSV 导出到 Azure Data Lake Storage,但是当文件 system/container 不存在时代码中断。我也通读了documentation,但我似乎找不到任何对这种情况有帮助的东西。

如果用户指定的容器不存在,我该如何在 Azure Data Lake Storage 中创建容器?

当前代码:

    try:
        file_system_client = service_client.get_file_system_client(file_system="testfilesystem")
    except Exception:
        file_system_client = service_client.create_file_system(file_system="testfilesystem")

回溯:

(FilesystemNotFound) The specified filesystem does not exist.
RequestId:XXXX
Time:2021-03-31T13:39:21.8860233Z

不应在此处使用 try catch 模式,因为 Azure Data lake gen2 library 具有针对 file_system_client 的内置 exists() method

首先,确保您已经安装了最新版本的库azure-storage-file-datalake 12.3.0。如果您不确定您使用的是哪个版本,请使用 pip show azure-storage-file-datalake 命令检查当前版本。

那么您可以使用下面的代码:

from azure.storage.filedatalake import DataLakeServiceClient

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

#the get_file_system_client method will not throw error if the file system does not exist, if you're using the latest library 12.3.0
file_system_client = service_client.get_file_system_client("filesystem333")

print("the file system exists: " + str(file_system_client.exists()))

#create the file system if it does not exist
if not file_system_client.exists():
    file_system_client.create_file_system()
    print("the file system is created.")

#other code

我在本地测试过,可以正常运行: