簡體   English   中英

在 python3 中獲取 aws s3 ls s3://mybucket/mykey/ 的結果

[英]Get the result of aws s3 ls s3://mybucket/mykey/ in python3

如何在 python 中檢索 bash 命令的相同結果?

我嘗試使用 boto3 中的 list_objects_v2 ,但我不想要所有對象,只想要下一個文件名。

您似乎想從對象列表中排除前綴路徑。

Amazon S3 中對象的名稱(鍵)包括其完整路徑。 因此,您可以簡單地從鍵中刪除前綴:

import boto3

s3_resource = boto3.resource('s3')

PREFIX = 'mykey/'

for object in s3_resource.Bucket('my-bucket').objects.filter(Prefix=PREFIX):
    print(object.key[len(PREFIX):]) # This skips-over the prefix

這是使用boto3.client的等價物:

import boto3

s3_client = boto3.client('s3')

PREFIX = 'mykey/'

response = s3_client.list_objects_v2(Bucket='my-bucket', Prefix=PREFIX)

for object in response['Contents']:
    print(object['Key'][len(PREFIX):]) # This skips-over the prefix

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM