如何将文件夹上传到Azure blob存储,同时在Python中保留结构?

8fq7wneg  于 2022-12-19  发布在  Python
关注(0)|答案(1)|浏览(137)

我编写了以下代码,使用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"))

这个工作很好。我想知道我怎么才能上载整个文件夹,里面有所有的文件和子文件夹,同时保持我的本地文件夹的结构完整?

q3qa4bjr

q3qa4bjr1#

从我的复制结束后,我可以使用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

结果:

相关问题