Issue
I have a s3 bucket named 'Sample_Bucket' in which there is a folder called 'Sample_Folder'. I need to get only the names of all the files in the folder 'Sample_Folder'.
I am using the following code to do so -
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)
The variable files contain object variables which has the filename as key.
s3.ObjectSummary(bucket_name='Sample-Bucket', key='Sample_Folder/Sample_File.txt')
But I need only the filename. How do I extract that? Or is there any other way to do it?
Solution
You should use list_object_v2 which gives you the list from the defined prefix used.
... 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)
Answered By - ZF007
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.