如何在 python 中打印 S3 密钥名称

How to print the S3 key name in python

我已经为新对象的所有放置添加了 S3 触发器并调用了 AWS Lambda。

我的 Lambda 是用 Python 3.8 编写的,用于解析关键对象和文件并获取文件名。

import urllib.parse
import boto3

print('Loading function')

s3 = boto3.client('s3')


def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
    try:
        print(key)

一旦我上传mys3bucket/jsonfiles/2021/05/31/file.json

我的代码打印 jsonfiles/2021/05/31/file.json, 我想打印的是。

key1 as 2021/05/31/, omitting the jsonfiles prefix
and
key2 as file.json, printing just the file name.

我的代码应该是什么样的?

一旦你得到 key 做一些字符串解析并从中获取你需要的数据,

>>> s = "mys3bucket/jsonfiles/2021/05/31/file.json"
>>> s.split("jsonfiles/")
['mys3bucket/', '2021/05/31/file.json']
>>> req = s.split("jsonfiles/")[1]
>>> ind = req.rfind('/')
>>> req[:ind]
'2021/05/31'
>>> req[ind + 1:]
'file.json'