【问题标题】:read only particular json files from s3 buckets from multiple folders仅从多个文件夹的 s3 存储桶中读取特定的 json 文件
【发布时间】:2020-06-30 03:18:39
【问题描述】:

我正在尝试滚动 s3 中的所有存储桶并查看是否有匹配的前缀并进入这些文件夹并读取 json 文件。

我已尝试获取包含前缀的文件夹,但无法输入。

代码:

import boto3
bucket = ['test-eob', 'test-eob-images']
client = boto3.client('s3')
for i in bucket:
    result = client.list_objects(Bucket=i,Prefix = 'PROCESSED_BY/FILE_JSON', Delimiter='/')
    print(result)

使用它会得到带有前缀的那些,而当桶没有那个前缀时会失败。

test-eobtest-eob/PROCESSED_BY/FILE_JSON/*.json 的结构 如果只有我的前缀匹配,我必须读取 json,否则从桶中出来。

谁能帮帮我。

【问题讨论】:

    标签: python amazon-web-services amazon-s3


    【解决方案1】:

    当桶不包含前缀时,尝试捕获错误(是KeyError?)。

    例如:

    for i in bucket:
        try:
              result = client.list_objects(Bucket=i,Prefix = 'PROCESSED_BY/FILE_JSON', Delimiter='/')
              print(result)
        except KeyError:
              pass
    

    要读取 json,有几种方法。例如来自 json 模块的json.loads()

    所以对于桶中的每个对象:

    content_object = s3.Object(bucket_name, file_name)
    file_content = content_object.get()['Body'].read().decode('utf-8')
    json_content = json.loads(file_content)
    

    【讨论】:

    • 所以我必须在 print(result) 之后插入 json 代码对吗?
    • 是的,您已经为每个 json 对象执行此操作。
    • 好的,谢谢。有什么困难我会告诉你的。
    • 嘿嘿所以我有四种json,命名为666-Account.json77-Account.json22-Multi.json等等……我只想读*Account.json。我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2021-07-03
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多