【问题标题】:Open file from Azure Blob Storage and append them in a new file从 Azure Blob 存储打开文件并将它们附加到新文件中
【发布时间】:2020-10-15 13:46:02
【问题描述】:

我似乎无法解决这个问题。

我在 Azure 容器中有几个名为 container1 的文件。例如:

s1_cat.json
s2_cat.json
s3_dog.json
s1_dog.json
s2_dog.json

每个 json 的内容示例如下所示,例如 s1_cat.json

{"abc" : "def", "ghi" : 0}
{"123" : "456", "789" : 1}

s2_cat.json:

{"klm" : "nop", "qrs" : 2}
{"2203" : "1994", "000" : 3}

很难处理正确的 json 格式。 无论如何,我想根据关键字 catdog 将它们附加到一个新文件到另一个名为 temp 的容器中,就像这样(如 cat.json):

{"abc" : "def", "ghi" : 0}
{"123" : "456", "789" : 1}
{"klm" : "nop", "qrs" : 2}
{"2203" : "1994", "000" : 3}

我当前的代码:

try:

    container_name = 'container1'
    filepath = 'temp'
    account_name = 'xxx'
    account_key = 'xxx'

    blobService = BlockBlobService(account_name=account_name, account_key=account_key)
    appendblobservice = AppendBlobService(account_name=account_name, account_key=account_key)

    data = blobService.list_blobs(container_name, prefix='temp')

       
    for blob in data:

        if 'cat' in blob.name :

            filename = "cat.json"

            blobService.get_blob_to_path(container_name, blob_name=blob.name, file_path=filepath)

            #I stuck from here.....
            #read the json file
            cat = blobService.get_blob_to_text(container_name, blob.name)
            cat = cat.content.split('\n')
            cat = list(filter(None, cat )) #remove empty element in the list
            #display result
            print(cat)
            #stuck here....                



    
except Exception as ex:
    print('Unable to connect!')
    print('Exception:')
    print(ex)

我的问题是我不知道如何将第一个 cat 附加到第二个 cat 文件中。我只设法显示它们。我怎样才能做到这一点?

【问题讨论】:

  • 能否在循环前定义一个字符串,然后在每个循环中,将内容添加到字符串中?
  • 字符串是什么意思?如果你不介意,你可以展示一下。 @IvanYang
  • 在下面查看,如果我误解了你,请纠正我。
  • 嗨@IvanYang。抱歉迟了回应。它对我不起作用。相反,我创建了一个新列表并附加到它。但是,我现在正在寻找不同的方法。感谢您的跟进!
  • 如果您找到好的解决方案,请与我们分享。你也可以详细说明你的问题,然后我可以继续跟进:)。

标签: python json azure azure-blob-storage


【解决方案1】:

尝试定义一个字符串,然后在每个循环中将每个内容添加到字符串中。代码如下:

#other code

mystring=""

for blob in data:

        if 'cat' in blob.name :

            filename = "cat.json"

            blobService.get_blob_to_path(container_name, blob_name=blob.name, file_path=filepath)

            #I stuck from here.....
            #read the json file
            cat = blobService.get_blob_to_text(container_name, blob.name)
            cat = cat.content.split('\n')
            cat = list(filter(None, cat )) #remove empty element in the list
            #display result
            print(cat)

            #here, append each content to the string
            mystring += cat + "\n"

            #stuck here....   

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 2020-06-17
    • 2021-07-29
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 2020-08-25
    • 2021-05-06
    相关资源
    最近更新 更多