首页 > 解决方案 > 使用 Python 从 Azure 容器读取文件的动态文件路径?

问题描述

我必须每天根据输入文件获取一个文件并运行代码。此文件位于容器中的 Azure 存储上,并且需要在上传文件时自动运行代码。

文件路径如下:

path = f"adls:/{container_name}/{folder}/" + str(year) + "/" + str(month) + "/" + str(day)
file_name = "data_"+str(year)+"_"+str(month)+"_"+str(day)+".csv"

由于格式,文件名每天都会更改。上传此文件的文件夹也会每天更改。

这是我到目前为止所做的:

def find_file(current_date, path):
    current_date = datetime.datetime.now()
    year = current_time.year
    month = current_time.month
    day = current_time.day

    path = f"adls:/{container_name}/{folder}/" + str(year) + "/" + str(month) + "/" + str(day)
    file = "data_"+str(year)+"_"+str(month)+"_"+str(day)+".csv"

    if os.path.isfile(path) and os.access(path, os.R_OK):
       print("File exists and is readable")
    else:
       print("Either the file is missing or not readable")
       sys.exit()

    return file

find_file(current_date, path)

我正在检查文件是否存在于给定路径中。如果存在具有给定名称的文件,则代码应运行并读取该文件,否则代码应中止。

上面的代码显然是不正确的。我是 Python 函数的新手。有人可以纠正我哪里错了吗?

标签: pythonazurepathfilepath

解决方案


如果要确定 Azure 存储上是否存在文件,请使用该exists方法。你可以参考这里

from azure.storage.blob import BlobServiceClient

blob_service_client = BlobServiceClient.from_connection_string("connection_string")
blob_client = blob_service_client.get_blob_client(container="container_name", blob="my_blob")

isExist = blob_client.exists()
print(isExist)

if isExist:
    # download blob file
    stream = blob_client.download_blob()
    print("File exists and is readable")
else:
    print("Either the file is missing or not readable")

推荐阅读