首页 > 解决方案 > 通过 python 检查 azure data Lake Storage gen2 中是否存在文件

问题描述

嗨,我想知道 ADLS Gen 2 中的文件存在

file_client = service_client.get_file_client(file_system='filelayer', file_path='my_file.txt')  

这给出了file_client,但是如何检查文件是否存在,因为我试图重命名它并给出错误(如果不存在):

(SourcePathNotFound) The source path for a rename operation does not exist

所以我只想file_client.rename_file(target_name)在文件存在时才进行重命名。

标签: python-3.xazure-data-lake-gen2

解决方案


没有 file_exists,但您可以使用 get_file_properties()


def exists(file_client: DataLakeFileClient):
    try:
        file_client.get_file_properties()
        return True
    except ResourceNotFoundError:
        return False

file_client = service_client.get_file_client(file_system='filelayer', file_path='my_file.txt')  
if exists(file_client):
   file_client.rename_file(targetName)

但是,有些人(包括我)考虑了直接通过 try/catch 来解决问题的 Pythonic 方法:

file_client = service_client.get_file_client(file_system='filelayer', file_path='my_file.txt')

try: 
   file_client.rename(target_name)
except ResourceNotFoundError: 
   # log that the files does not exist or not, up to you
   pass
``

推荐阅读