对于第2代Python 3.8 Azure数据湖,如何检查文件系统上是否存在文件?

时间:2020-08-25 15:08:54

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

我正在使用Python 3.8,Azure Data Lake gen 2和以下插件...

azure-storage-blob==12.4.0
azure-storage-file-datalake==12.1.1

如何检查文件系统上是否存在特定路径?我尝试过了

from azure.storage.filedatalake import DataLakeFileClient

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

但是出现一个错误,即DataLakeFileClient不存在“ exists”方法。

2 个答案:

答案 0 :(得分:0)

如果要检查文件系统上是否存在文件,请参考以下代码

from azure.storage.filedatalake import DataLakeFileClient

account_name = 'testadls05'
account_key = 'CpfCQot******JOLvB+aJOZbsQ=='
file_system_name='test'
file_client = DataLakeFileClient(account_url="{}://{}.dfs.core.windows.net".format(
        "https",
        account_name
    ),
    file_system_name=file_system_name,
    file_path='test.txt',
    credential=account_key 
)

try:
     file_client.get_file_properties()
except Exception as error:
    print(error)    
    if type(error).__name__ =='ResourceNotFoundError':
        print("the path does not exist")

enter image description here

答案 1 :(得分:0)

一种更简单的方法来测试文件或路径是否存在:

from azure.storage.filedatalake import DataLakeServiceClient
...
try:
    file_system_client = service_client.get_file_system_client(file_system="my-file-system")
    if file_system_client.get_file_client("my-file").exists():
        print("file exists")
    else:
        print("file does not exist")

except Exception as e:
    print(e)

get_file_client() 更改为 get_directory_client() 以测试路径。