Reputation: 1055
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?
Upvotes: 11
Views: 58051
Reputation: 3731
You should use list_object_v2 which gives you the list from the defined prefix used.
... snippet ...
filenames = []
def get_filenames(s3):
result = s3.list_objects_v2(Bucket=bucket, Prefix=prefix)
for item in result['Contents']:
files = item['Key']
print("file: ", files)
filenames.append(files) #optional if you have more filefolders to got through.
return filenames
get_filenames(my_bucketfolder)
Upvotes: 5
Reputation: 609
If you don't want to use boto3.client
and prefer boto3.resource
you can use this snippet to list all the directory names within a directory.
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'))
Upvotes: 0
Reputation: 2758
for myself, i made a function that you might find helpful:
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')]
Upvotes: 1
Reputation: 249
Here you go.
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()]
Upvotes: 12