【问题标题】:Dynamic file path to read a file from Azure Container using Python?使用 Python 从 Azure 容器读取文件的动态文件路径?
【发布时间】:2020-10-16 06:37:28
【问题描述】:

我必须每天根据输入文件获取一个文件并运行代码。此文件位于容器中的 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 函数的新手。有人可以纠正我哪里出错了吗?

【问题讨论】:

    标签: python azure path filepath


    【解决方案1】:

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

    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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 2021-06-25
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 2019-02-01
      • 2021-07-24
      相关资源
      最近更新 更多