[英]Get only file names from s3 bucket folder
我有一個名為“Sample_Bucket”的 s3 存儲桶,其中有一個名為“Sample_Folder”的文件夾。 我只需要獲取文件夾“Sample_Folder”中所有文件的名稱。
我正在使用以下代碼來這樣做 -
import boto3
s3 = boto3.resource('s3', region_name='us-east-1', verify=False)
bucket = s3.Bucket('Sample_Bucket')
for files in bucket.objects.filter(Prefix='Sample_Folder):
print(files)
變量文件包含以文件名作為關鍵字的對象變量。
s3.ObjectSummary(bucket_name='Sample-Bucket', key='Sample_Folder/Sample_File.txt')
但我只需要文件名。 我如何提取它? 或者有其他方法可以做到嗎?
干得好。
import boto3
bucket = "Sample_Bucket"
folder = "Sample_Folder"
s3 = boto3.resource("s3")
s3_bucket = s3.Bucket(bucket)
files_in_s3 = [f.key.split(folder + "/")[1] for f in s3_bucket.objects.filter(Prefix=folder).all()]
您應該使用 list_object_v2 ,它為您提供使用的定義前綴中的列表。
... snippet ...
filenames = []
get_filenames(s3):
result = s3.list_objects_v2(Bucket=bucket, Prefix=prefix)
for item in result['Contents']:
files = item['Key']
print(files)
filenames.append(files) #optional if you have more filefolders to got through.
return filenames
get_filenames(my_bucketfolder)
對於我自己,我做了一個你可能會覺得有用的函數:
import boto3
s3_client = boto3.client('s3')
def list_objects_without_response_metadata(**kwargs):
ContinuationToken = None
while True:
if ContinuationToken:
kwargs["ContinuationToken"] = ContinuationToken
res = s3_client.list_objects_v2(**kwargs)
for obj in res["Contents"]:
yield obj
ContinuationToken = res.get("NextContinuationToken", None)
if not ContinuationToken:
break
file_names = [obj["Key"] for obj in list_objects_without_response_metadata(Bucket='Sample_Bucket', Prefix='Sample_Folder')]
如果您不想使用boto3.client
而更喜歡boto3.resource
,則可以使用此代碼段列出目錄中的所有目錄名稱。
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket("Sample_Bucket")
res = bucket.meta.client.list_objects(Bucket=bucket.name, Delimiter='/', Prefix = "Sample_Folder/"')
for o in res.get('CommonPrefixes'):
print(o.get('Prefix'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.