首页 > 解决方案 > Python:如何从 azure blob 存储中读取 doc 文件?

问题描述

我在 blob 存储中有一个 docx 文件。

我尝试做的是获取 blob 中文件的链接/路径或 url 以应用此功能:

def get_docx_text(path):
    """
    Take the path of a docx file as argument, return the text in unicode.
    """
    document = zipfile.ZipFile(path)
    xml_content = document.read('word/document.xml')
    document.close()
    tree = XML(xml_content)

    paragraphs = []
    for paragraph in tree.getiterator(PARA):
        texts = [node.text
                 for node in paragraph.getiterator(TEXT)
                 if node.text]
        if texts:
            paragraphs.append(''.join(texts))

    text = '\n\n'.join(paragraphs)
    return (paragraphs,text)

在 def get_docx_text(path) 的参数路径中,我想放置文件的路径。

我怎样才能做到这一点 ?

我尝试过这样的事情但不起作用:

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient

connection_string='...'
blob_service_client = BlobServiceClient.from_connection_string(connection_string)

service_client = BlobServiceClient.from_connection_string(connection_string)

client = service_client.get_container_client("name_container")

bc = client.get_blob_client(blob="bronze/txt_name.docx")

with open("txt_name.docx", 'wb') as file:

    data = bc.download_blob()

    file.write(data.readall())

标签: pythonazure-blob-storage

解决方案


感谢Gaurav在评论中提供您的建议,将其转换为帮助其他社区成员的答案。

问题: ResourceNotFoundError: The specified blob does not exist

解决方案:请尝试使用此代码

bc = client.get_blob_client(blob="sink/bronze/txt_name.docx")

由于您在运行代码的同一文件夹中下载 blob,因此您只需指定保存文件的名称。

例如:在这段代码中

with open("txt_name.docx", 'wb') as file:

推荐阅读