Below piece of code returns ONLY the 'subfolders' in a 'folder' from s3 bucket.

import boto3
bucket = 'my-bucket'
#Make sure you provide / in the end
prefix = 'prefix-name-with-slash/'  

client = boto3.client('s3')
result = client.list_objects(Bucket=bucket, Prefix=prefix, Delimiter='/')
for o in result.get('CommonPrefixes'):
    print 'sub folder : ', o.get('Prefix')

For more details, you can refer to https://github.com/boto/boto3/issues/134

Answer from Dipankar on Stack Overflow
Top answer
1 of 16
186

Below piece of code returns ONLY the 'subfolders' in a 'folder' from s3 bucket.

import boto3
bucket = 'my-bucket'
#Make sure you provide / in the end
prefix = 'prefix-name-with-slash/'  

client = boto3.client('s3')
result = client.list_objects(Bucket=bucket, Prefix=prefix, Delimiter='/')
for o in result.get('CommonPrefixes'):
    print 'sub folder : ', o.get('Prefix')

For more details, you can refer to https://github.com/boto/boto3/issues/134

2 of 16
126

S3 is an object storage, it doesn't have real directory structure. The "/" is rather cosmetic. One reason that people want to have a directory structure, because they can maintain/prune/add a tree to the application. For S3, you treat such structure as sort of index or search tag.

To manipulate object in S3, you need boto3.client or boto3.resource, e.g. To list all object

import boto3 
s3 = boto3.client("s3")
all_objects = s3.list_objects(Bucket = 'bucket-name') 

http://boto3.readthedocs.org/en/latest/reference/services/s3.html#S3.Client.list_objects

In fact, if the s3 object name is stored using '/' separator. The more recent version of list_objects (list_objects_v2) allows you to limit the response to keys that begin with the specified prefix.

To limit the items to items under certain sub-folders:

    import boto3 
    s3 = boto3.client("s3")
    response = s3.list_objects_v2(
            Bucket=BUCKET,
            Prefix ='DIR1/DIR2',
            MaxKeys=100 )

Documentation

Another option is using python os.path function to extract the folder prefix. Problem is that this will require listing objects from undesired directories.

import os
s3_key = 'first-level/1456753904534/part-00014'
filename = os.path.basename(s3_key) 
foldername = os.path.dirname(s3_key)

# if you are not using conventional delimiter like '#' 
s3_key = 'first-level#1456753904534#part-00014'
filename = s3_key.split("#")[-1]

A reminder about boto3 : boto3.resource is a nice high level API. There are pros and cons using boto3.client vs boto3.resource. If you develop internal shared library, using boto3.resource will give you a blackbox layer over the resources used.

Top answer
1 of 2
4

You can enumerate through all of the objects in the bucket, and find the "folder" (really the prefix up until the last delimiter), and build up a list of available folders:

seen = set()
s3 = boto3.client('s3')
paginator = s3.get_paginator('list_objects_v2')
for page in paginator.paginate(Bucket='bucket-name'):
    for obj in page.get('Contents', []):
        key = obj['Key']
        folder = key[:key.rindex("/")] if '/' in key else ""
        if folder not in seen:
            seen.add(folder)
            print(folder)

Alternatively, you could use the same basic logic of recursion that you were using, only with multiple workers, allowing you to alleviate some of the time spent waiting for replies:

def recursion_worker(bucket_name, prefix):
    # Look in the bucket at the given prefix, and return a list of folders
    s3 = boto3.client('s3')
    paginator = s3.get_paginator('list_objects_v2')

    folders = []
    for page in paginator.paginate(Bucket=bucket_name, Prefix=prefix, Delimiter='/'):
        for sub_prefix in page.get('CommonPrefixes', []):
            folders.append(sub_prefix['Prefix'])
        # S3 returns common prefixes first, if there are any objects, it 
        # means further pages will just return objects, so no need
        # to keep going
        # Note that this isn't a garuanteed order, though it's unlikely
        # to change. To be 100% safe, don't do this check at the expense
        # of a slower result set for large buckets
        if len(page.get('Contents', [])) > 0:
            break

    return folders

def folders_via_recursion():
    import multiprocessing
    from collections import deque

    bucket_name = 'example-bucket'
    folders = []
    # Spin up many workers, more than we have CPU cores for
    # since most of the workers will be spending most
    # of their time waiting for network traffic
    with multiprocessing.Pool(processes=32) as pool:
        pending = deque()
        # Seed the workers with the first request to list objects at
        # the root of the bucket
        pending.append(pool.apply_async(recursion_worker, (bucket_name, "")))
        while len(pending) > 0:
            # Keep going while there are items to parse
            temp = pending.popleft()
            for cur in temp.get():
                # Print out every folder, and store the result in an array
                # to consume later on
                print(cur)
                folders.append(cur)
                # And tell a free worker to list out the folder we just found
                pending.append(pool.apply_async(recursion_worker, (bucket_name, cur)))

    # All done, we can consume the folders array as needed, though
    # do note, it's in a somewhat random order, run something like
    # folders.sort()
    # first if you want a stable order before looking at it

If even this fails, then your bucket is simply too big to parse in one go in a Lambda. You'll need to consider some other solution to get a list of files, like using AWS S3 Inventory to create a list of objects outside of this Lambda that it can process.

2 of 2
1

The list_objects_v2() call returns a list of all objects. The Key of each object includes the full path of the object.

Therefore, you can simply extract the paths from the Keys of all objects:

import boto3

s3_client = boto3.client('s3')

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

# folder1/folder2/foo.txt --> folder1/folder2
paths = {object['Key'][:object['Key'].rfind('/')] for object in response['Contents'] if '/' in object['Key']}

for path in sorted(paths):
    print(path)

If your bucket contains more than 1000 objects, then you will either need to loop through the results using ContinuationToken or use a paginator. See: list_objects_v2 paginator

Discussions

How do you list the most recent subfolder on s3 using boto3?
S3 is a key-based store, the concept of folders and subfolders does not exist beyond the AWS GUI which itself is just splitting keys on '/' characters for the sake of user convenience. It would be somewhat roundabout, but you could use the boto3 api to list all keys starting with a prefix such as /Cupcake/ and manually sift through the modified/creation timestamps to find the newest unique entry More on reddit.com
🌐 r/aws
11
14
May 15, 2021
How to list out all the folders inside a parent folder (or prefix) in a s3 bucket?
I'm sure somewhere inside the guts of S3, there is a very compelling reason they don't provide that wrapper. They generally won't provide a feature that will compromise the performance of the service, so that would be my guess. To answer your question, my first instinct is to change the way you are thinking about S3. It's not files in folders, but a huge list of objects, with some prefix data. Think of it as a flat list of files, with some fake "folders" in the UI. If you can't change your application to fit this new paradigm, then your only real option is a lot of list object calls. Depending on your number of objects, this could get expensive in both API calls and computation to sort through the lists looking for the prefixes you need. More on reddit.com
🌐 r/aws
7
1
July 1, 2021
python - Listing contents of a bucket with boto3 - Stack Overflow
So you're asking for the equivalent of aws s3 ls in boto3. This would be listing all the top level folders and files. This is the closest I could get; it only lists all the top level folders. Surprising how difficult such a simple operation is. Copyimport boto3 def s3_ls(): s3 = boto3.resource('s3') bucket ... More on stackoverflow.com
🌐 stackoverflow.com
How get just a folder from s3 bucket using boto3?
There is no such thing as a folder in S3. It is a key/value store where each key looks like what you’re used to a file path looking like. More on reddit.com
🌐 r/django
1
0
December 16, 2018
🌐
Habil
habil.dev › how-to-list-aws-s3-directory-contents-using-python-and-boto3
How to List AWS S3 Directory Contents Using Python and Boto3
May 21, 2026 - In this article, we'll explore how to use Python and boto3 to list directory contents in an S3 bucket. ... import boto3 import csv def list_bucket(): # Configuration bucket = "your-bucket-name" folder = "path/to/folder" # Initialize S3 client s3 = boto3.resource("s3", aws_access_key_id="YOUR_ACCESS_KEY", aws_secret_access_key="YOUR_SECRET_KEY" ) # Get bucket reference s3_bucket = s3.Bucket(bucket) # List files and extract relative paths files_in_s3 = [ f.key.split(folder + "/")[1] for f in s3_bucket.objects.filter(Prefix=folder).all() ] # Write results to file with open('bucket-contents.txt', 'w', encoding='UTF8') as file: file.write(str(files_in_s3)) if name == 'main': list_bucket()
🌐
Amazon Web Services
boto3.amazonaws.com › v1 › documentation › api › latest › reference › services › s3 › client › list_directory_buckets.html
list_directory_buckets - Boto3 1.43.36 documentation
Do you have a suggestion to improve this website or boto3? Give us feedback. ... Returns a list of all Amazon S3 directory buckets owned by the authenticated sender of the request. For more information about directory buckets, see Directory buckets in the Amazon S3 User Guide.
🌐
Plain English
plainenglish.io › home › blog › aws › aws lambda: get a list of folders in the s3 bucket
AWS Lambda: Get a List of Folders in the S3 Bucket
January 23, 2024 - The code begins by importing the necessary libraries, namely boto3 for interacting with AWS services and botocore for handling exceptions. The list_files_in_folder function takes two parameters - bucket_name and folder_prefix.
🌐
Medium
habil.medium.com › how-to-list-aws-s3-directory-contents-using-python-and-boto3-6281f5c3dea3
How to List AWS S3 Directory Contents Using Python and Boto3 | by Habil BOZALİ | Medium
February 26, 2025 - In this article, we’ll explore how to use Python and boto3 to list directory contents in an S3 bucket. ... import boto3 import csv def list_bucket(): # Configuration bucket = "your-bucket-name" folder = "path/to/folder" # Initialize S3 client s3 = boto3.resource("s3", aws_access_key_id="YOUR_ACCESS_KEY", aws_secret_access_key="YOUR_SECRET_KEY" ) # Get bucket reference s3_bucket = s3.Bucket(bucket) # List files and extract relative paths files_in_s3 = [ f.key.split(folder + "/")[1] for f in s3_bucket.objects.filter(Prefix=folder).all() ] # Write results to file with open('bucket-contents.txt', 'w', encoding='UTF8') as file: file.write(str(files_in_s3)) if name == 'main': list_bucket()
Find elsewhere
🌐
DEV Community
dev.to › aws-builders › how-to-list-contents-of-s3-bucket-using-boto3-python-47mm
How to List Contents of s3 Bucket Using Boto3 Python? - DEV Community
October 12, 2021 - You'll use boto3 resource and boto3 client to list the contents and also use the filtering methods to list specific file types and list files from the specific directory of the S3 Bucket.
🌐
GeeksforGeeks
geeksforgeeks.org › devops › how-to-retrieve-the-sub-folders-names-in-s3-bucket-using-boto3
How To Retrieve the Sub Folders Names In S3 Bucket Using Boto3? - GeeksforGeeks
July 23, 2025 - First, set up your AWS credentials and install boto3. Use the S3 client to list objects prefixed with the same term followed by a delimiter to indicate folder structures. Implement pagination to work with large datasets efficiently, making sure ...
🌐
Moonbooks
en.moonbooks.org › Articles › How-to-get-all-file-names-in-a-specific-AWS-S3-bucket-directory-using-python-
How to Get All File or Directory Names in a Specific AWS S3 Bucket Directory Using Python ?
August 22, 2023 - In this guide, we show how to use Python and the boto3 library to retrieve: ... We’ll use NOAA's noaa-nesdis-snpp-pds public bucket as an example, which contains a wide variety of satellite products. ... If you'd rather get a list of all top-level folders (or subfolders under a given prefix), use the S3 client interface with the Delimiter parameter:
🌐
Medium
aws.plainenglish.io › aws-lambda-code-to-list-folders-in-s3-bucket-cff7d9ec5726
AWS Lambda: Get a List of Folders in the S3 Bucket | by John Sener | AWS in Plain English
January 29, 2024 - The code begins by importing the necessary libraries, namely boto3 for interacting with AWS services and botocore for handling exceptions. The list_files_in_folder function takes two parameters - bucket_name and folder_prefix.
🌐
Binary Guy
binaryguy.tech › aws › s3 › quickest-ways-to-list-files-in-s3-bucket
Quickest Ways to List Files in S3 Bucket - Binary Guy
November 24, 2024 - s3 = boto3.client("s3", ... but just list files from one folder. In that case, we can use list_objects_v2 and pass which prefix as the folder name....
🌐
Reddit
reddit.com › r/aws › how to list out all the folders inside a parent folder (or prefix) in a s3 bucket?
r/aws on Reddit: How to list out all the folders inside a parent folder (or prefix) in a s3 bucket?
July 1, 2021 -

I need to check if a folder exists inside a parent folder in s3 bucket. Since there is no direct way, I thought of using list_objects method of boto3 to list out all the objects in a folder and then search for the folder name in the results.

But, how can I get the names of all the folders inside a parent folder (or s3 prefix) with list_objects method?

I find the usage of delimiter and prefixes to be confusing. Especially delimiter. Why there is not a simple way to list files and directories just like in the Unix system. I understand s3 is not a file system but they can provide a wrapper function for it.

🌐
Codegive
codegive.com › blog › boto3_list_files_in_bucket_folder.php
Boto3 List Files in Bucket Folder (2026): The Ultimate Guide to Effortless AWS S3 Object Management
By the end of this guide, you'll ... folder," we're referring to the process of programmatically fetching a list of objects (files) that reside within a specific path (or "folder") inside an Amazon S3 bucket, using the AWS SDK for Python, boto3....
🌐
CSDN
devpress.csdn.net › python › 62fd306cc677032930802f12.html
Retrieving subfolders names in S3 bucket from boto3_python_Mangs-Python
import boto3 s3 = boto3.client("s3") all_objects = s3.list_objects(Bucket = 'bucket-name') http://boto3.readthedocs.org/en/latest/reference/services/s3.html#S3.Client.list_objects · In fact, if the s3 object name is stored using '/' separator. The more recent version of list_objects (list_objects_v2) allows you to limit the response to keys that begin with the specified prefix. To limit the items to items under certain sub-folders:
🌐
Google APIs
storage.googleapis.com › dtppnvplstvxye › boto3-get-list-of-folders-in-bucket.html
Boto3 Get List Of Folders In Bucket at Emma Getz blog
April 5, 2025 - Learn how to use the list_buckets() ... files/objects inside a specific folder within an s3 bucket then you will need to use the list_objects_v2 method with the....