簡體   English   中英

如何將a文件夾上傳到Azure blob存儲中,同時保留Python中的結構?

[英]How to upload the a folder into Azure blob storage while preserving the structure in Python?

我編寫了以下代碼,使用 Python 將文件上傳到 blob 存儲中:

blob_service_client = ContainerClient(account_url="https://{}.blob.core.windows.net".format(ACCOUNT_NAME),
                                          credential=ACCOUNT_KEY,
                                          container_name=CONTAINER_NAME)

blob_service_client.upload_blob("my_file.txt", open("my_file.txt", "rb"))

這很好用。 我想知道如何在保持本地文件夾結構不變的情況下上傳包含所有文件和子文件夾的整個文件夾?

從我的最后復制后,我可以使用os模塊實現您的要求。 以下是對我有用的完整代碼。

dir_path = r'<YOUR_LOCAL_FOLDER>'

for path, subdirs, files in os.walk(dir_path):
    for name in files:
        fullPath=os.path.join(path, name)
        print("FullPath : "+fullPath)
        file=fullPath.replace(dir_path,'')
        fileName=file[1:len(file)];
        print("File Name :"+fileName)
        
        # Create a blob client using the local file name as the name for the blob
        blob_service_client = ContainerClient(account_url=ACCOUNT_URL,
                                          credential=ACCOUNT_KEY,
                                          container_name=CONTAINER_NAME)

        print("\nUploading to Azure Storage as blob:\n\t" + fileName)
        blob_service_client.upload_blob(fileName, open(fullPath, "rb"))
        

下面是我本地的文件夾結構。

├───g.txt
├───h.txt
├───Folder1
    ├───z.txt
    ├───y.txt
├───Folder2
    ├───a.txt
    ├───b.txt
    ├───SubFolder1
        ├───c.txt
        ├───d.txt

結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM