Python-从路径获取AWS Bucket密钥

时间:2020-06-17 04:20:27

标签: python-3.x amazon-web-services amazon-s3 boto3

鉴于我有这样的东西:

"s3://folder1/folder2/folder3/folder4/folder4.5/folder4.6/folder5/folder6/folder7/file_name.csv"

我该如何解析它,以使我得到Bucket,然后得到Key,因为它减去文件名的last /?

我正在尝试获取路径,以便可以列出路径中的所有文件。

1 个答案:

答案 0 :(得分:1)

一种方法是使用简单的splitjoin组合:

s3_path = "s3://folder1/folder2/folder3/folder4/folder4.5/folder4.6/folder5/folder6/folder7/file_name.csv"

s3_path_split = s3_path.split('/')

bucket_name = s3_path_split[2]

# 'folder1'

key_name = '/'.join(s3_path_split[3:])

# 'folder2/folder3/folder4/folder4.5/folder4.6/folder5/folder6/folder7/file_name.csv'

key_name_without_file = '/'.join(s3_path_split[3:-1])

# folder2/folder3/folder4/folder4.5/folder4.6/folder5/folder6/folder7'