Get Filename List from S3 Bucket or a Specific Folder in Python

In this tutorial, we will show you how to retrieve filename list from S3 bucket or a specific S3 folder using the Boto3 Python library.

First, you must install the latest version of Boto3 Python library using the following command:


pip install boto3

The following is an example code to get filename list from S3 bucket:


import boto3
from botocore.exceptions import ClientError

ACCESS_SECRET = "your aws access secret"
ACCESS_KEY = "your aws access key"

s3_client = boto3.client('s3', region_name='us-east-1', aws_access_key_id=ACCESS_KEY,
                         aws_secret_access_key=ACCESS_SECRET)

# bucket name
bucket_name = "bucket-one"

# getting filename list from S3 Bucket
try:
    response = s3_client.list_object_versions(Bucket=bucket_name)
    file_list = []
    for item in response:
        key = item['Key']
        size = item['Size']
        file_list.append({'file_name': key, 'file_size': size})
    print(file_list)
except ClientError as ex:
    print("Error: ", ex)

The following is an example code to get filename list from a specific S3 folder:


import boto3
from botocore.exceptions import ClientError

ACCESS_SECRET = "your aws access secret"
ACCESS_KEY = "your aws access key"

s3_client = boto3.client('s3', region_name='us-east-1', aws_access_key_id=ACCESS_KEY,
                         aws_secret_access_key=ACCESS_SECRET)

# bucket name
bucket_name = "bucket-one"

# folder path
prefix = "example-folder"

# getting filename list from S3 Bucket
try:
    response = s3_client.list_object_versions(Bucket=bucket_name, Prefix =prefix)
    file_list = []
    for item in response:
        key = item['Key']
        size = item['Size']
        file_list.append({'file_name': key, 'file_size': size})
    print(file_list)
except ClientError as ex:
    print("Error: ", ex)