使用带有Python V12 SDK的BlobServiceClient将本地文件夹上传到Azure Blob存储 [英] Upload local folder to Azure Blob Storage using BlobServiceClient with Python V12 SDK
问题描述
总结问题:
我正在尝试使用带有Python的BlobServiceClient将本地文件夹上传到Blob存储.一些问题此处不起作用,因为create_blob_from_path()
在V12 SDK中不起作用,并且我不想回到较早的版本.
I am trying to upload a local folder to Blob Storage using BlobServiceClient with Python. Some of the questions here and here do not work because create_blob_from_path()
doesn't work in V12 SDK and I wouldn't want to go back to older version.
我尝试过的事情:
我正在将os.walk
用于本地目录,但是缺少最重要的部分,例如类似于create_blob_from_path()
的功能.
I am using os.walk
for local directory but missing the most important part like a function similar to create_blob_from_path()
.
示例代码:
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, PublicAccess
import os
base_file_path = '/path/to/my/local/directory/'
connect_str = '1q2w3e4r5t6y'
container_name = 'abc'
try:
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = 'abc' # already created in Azure
container_client = blob_service_client.get_container_client(container_name)
upload_local_file_path = base_file_path + 'csv-summary-output' # input folder path
for root, subdir, local_file in os.walk(upload_local_file_path):
if local_file:
for name in local_file:
dir_part = os.path.relpath(root, upload_local_file_path)
file_path = os.path.join(root, name)
==> missing parts here
except Exception as ex:
print('Exception:')
print(ex)
我们非常感谢您的帮助,我将看看Azure Github,看看那里是否有用.
Any help is much appreciated and I will take a look at Azure Github to see if anything useful there.
推荐答案
您还可以使用下面的代码(假设本地文件夹位于D:\aaa
中,请根据需要随意修改代码):>
You can also use the code below(Assume the local folder is in D:\aaa
, please feel free to modify the code as per your need):
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient,PublicAccess
import os
def run_sample():
conn_str="xxx"
container_name="xxx"
path_remove = "D:\\"
local_path = "D:\\aaa" #the local folder
service_client=BlobServiceClient.from_connection_string(conn_str)
container_client = service_client.get_container_client(container_name)
for r,d,f in os.walk(local_path):
if f:
for file in f:
file_path_on_azure = os.path.join(r,file).replace(path_remove,"")
file_path_on_local = os.path.join(r,file)
blob_client = container_client.get_blob_client(file_path_on_azure)
with open(file_path_on_local,'rb') as data:
blob_client.upload_blob(data)
if __name__ == '__main__':
run_sample()
print("**completed**")
这篇关于使用带有Python V12 SDK的BlobServiceClient将本地文件夹上传到Azure Blob存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!