使用Python boto从S3获取文件元数据

问题描述 投票:0回答:2

我在AWS S3中有一些二进制文件,我需要使用file metadatacreated time获取modified time并使用Python Boto API访问时间?

我们尝试的是将文件复制到EC2实例,从那里我们使用os模块stat方法来获取时间。我希望当我们将文件复制到EC2实例时,这些细节会发生变化。

我试过的示例代码:

stat = os.stat(inputFile)
createdTime = datetime.fromtimestamp(stat[9]).strftime("%A, %B %d, %Y %I:%M:%S")

如何从S3直接获取这些细节?

python boto
2个回答
1
投票

Boto3有一个函数S3.Client.head_object

HEAD操作从对象检索元数据而不返回对象本身。如果您只对对象的元数据感兴趣,则此操作非常有用。

用于逐步执行存储桶中的文件并请求元数据的示例代码:

#! /usr/bin/python3

import boto3

paginator = s3client.get_paginator('list_objects_v2')
page_iterator = paginator.paginate(Bucket='MyBucketName')
for bucket in page_iterator:
    for file in bucket['Contents']:
        print(file['Key'])
        try:
            metadata = s3client.head_object(Bucket='MyBucketName', Key=file['Key'])
            print(metadata)
        except:
            print("Failed {}".format(file['Key']))

1
投票

使用boto3而不是boto。你可以看看https://boto3.readthedocs.io/en/latest/reference/services/s3.html有关boto3的s3 apis的任何信息。可用的过滤器不多,请检查您所需的过滤器是否可用。检查这一点以https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.list_objects_v2开头

© www.soinside.com 2019 - 2024. All rights reserved.