python - 从 Azure Blob 存储打开文件并将它们附加到新文件中
问题描述
我似乎无法解决这个问题。
我在 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 格式。无论如何,我想根据关键字将它们附加cat
到dog
一个新文件中,然后将它们附加到一个不同的容器中,temp
如下所示(as 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
文件中。我只设法显示它们。我怎样才能做到这一点?
解决方案
尝试定义一个字符串,然后在每个循环中将每个内容添加到字符串中。代码如下:
#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....
推荐阅读
- spring - SecurityContextHolder.getContext().getAuthentication() 从 @ControllerAdvice 类调用时返回 null
- python - 如何使用 for range 循环遍历 Python 中的两个列表?
- bash - 启用 bash-completion 会禁用自动完成文件名的默认行为
- node.js - Nodejs - 使用预签名的 url 从 s3 存储桶反应下载文件
- ruby-on-rails - 在 Rails 中使用 Pundit 限制整个控制器的 DRY 方法是什么?
- python - 当数据限制不同时创建具有多个轴的等宽(正方形)图?
- azure-service-fabric-mesh - 如何在 Azure 服务结构网格中为 Asp.net 核心应用程序启用 TLS SSL Https
- python - sqlalchemy 核心中的自引用列
- python-2.7 - 将偏移量转换为非偏移量的 Python 日期
- compiler-errors - 为什么我不能将 main.rs 添加到 crate 的源代码并导入结构?