使用Python将文本文件上载到Azure Blob-字节格式的本地变量错误

rqdpfwrv  于 2023-05-01  发布在  Python
关注(0)|答案(1)|浏览(83)

我目前正在做一个项目,我需要使用Python将本地文本文件上传到Azure Blob。我写了下面的代码来实现这一点:

def upload_blob(self, file_name, local_file_path):
file_name = 'upload_test.txt'
blob_service_client = BlobServiceClient.from_connection_string(self.storage_connection_str,timeout=120)

container_client = blob_service_client.get_container_client(self.storage_container_name)

# Define the directory path and filename
directory_name = self.blob_prefix

# Create a BlobClient object for the file
blob_client = container_client.get_blob_client(directory_name + "/" + file_name)

# Upload the file to the specified directory
with open(local_file_path, "rb") as data:
    blob_client.upload_blob(data)

然而,我遇到了一个错误,代码对于字节格式的局部变量运行良好,但在尝试上载本地文本文件时遇到了问题。
我对Python和Azure Blob相当陌生,所以我不太确定如何解决这个问题。有没有人遇到过类似的问题,并找到了解决方案?任何帮助或建议将不胜感激!
先谢谢你。

sdnqo3pr

sdnqo3pr1#

我遇到了一个错误,代码可以很好地处理字节格式的本地变量,但在尝试上传本地文本文件时遇到了问题。
您可以使用下面的代码使用Python将文件从本地上传到Azure Blob存储。

验证码:

from azure.storage.blob import BlobServiceClient

def uploadfile():
    connectionstring="your connection string"
    containername="test"
    filename="sample.txt"
    local_file_path="C:\\Users\\saswithip.txt"
    directory_name="folder1"
    client=BlobServiceClient.from_connection_string(connectionstring)
    container_client=client.get_container_client(containername)
    blob_client = container_client.get_blob_client(directory_name + "/" + filename)
    with open(local_file_path, "r", encoding="utf-8") as data:
       contents = data.read().encode("utf-8")
       blob_client.upload_blob(contents, overwrite=True)
       print("The file is uploaded successfully!!!")
uploadfile()

输出:

The file is uploaded successfully!!!

门户:

相关问题