繁体   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