且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Python递归将文件夹上传到Azure Blob存储

更新时间:2023-10-18 09:11:28

@Krumelur几乎是正确的,但是在这里我想给出一个有效的代码示例,并解释一些文件夹无法上传到Azure Blob存储中

@Krumelur is almost right, but here I want to give a working code example, as well as explain some folders are not be able to upload to azure blob storage.

1.代码示例:

from azure.storage.blob import BlockBlobService,PublicAccess
import os

def run_sample():
    account_name = "your_account_name"
    account_key ="your_account_key"
    block_blob_service = BlockBlobService(account_name, account_key)
    container_name ='test1'

    path_remove = "F:\\"
    local_path = "F:\\folderA"

    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)
                block_blob_service.create_blob_from_path(container_name,file_path_on_azure,file_path_on_local)            

# Main method.
if __name__ == '__main__':
    run_sample()

2.您应该记住,不能创建任何空文件夹,也不能将其上载到azure blob存储中,因为azure blob存储中没有真正的文件夹".文件夹或目录只是Blob名称的一部分.因此,如果在文件夹中没有真正的blob文件(如test.txt),则无法创建/上传空文件夹.因此,在您的文件夹结构中,空文件夹SUBFOLDERb和SUBFOLDERc无法上传到Azure Blob存储.

2.You should remember that any empty folder can not be created / uploaded to azure blob storage, since there is no real "folder" in azure blob storage. The folder or directory is just a part of the blob name. So without a real blob file like test.txt inside a folder, there is no way to create/upload an empty folder. So in your folder structure, the empty folder SUBFOLDERb and SUBFOLDERc are not be able to upload to azure blob storage.

测试结果如下,所有非空文件夹均以天蓝色上传到blob存储中:

The test result is as below, all the non-empty folders are uploaded to blob storage in azure: