Cloud Technology

How to list all files and folders within an S3 bucket using Boto3 in Python?

AL Asked by Alex Chen · 03-02-2025
0 upvotes 15,002 views 0 comments
The question

I am working on a Software Development project that involves auditing our AWS S3 storage. Since S3 is a flat storage system and doesn't use real folders, I am struggling to write a script that displays the hierarchy of "directories" and "files" correctly. How can I use the Boto3 library to iterate through a bucket and list both the prefixes and the object keys? Specifically, I need to know the difference between using the list_objects_v2 method versus the S3 Resource approach for large buckets.

3 answers

0
SA
Answered on 04-02-2025

The most efficient way to do this in a Software Development environment is using the list_objects_v2 method with the Delimiter parameter. Even though S3 is flat, setting Delimiter='/' tells AWS to treat the forward slash as a folder separator. You can then access "folders" via CommonPrefixes and "files" via Contents.

0
MI
Answered on 05-02-2025

If a bucket has more than 1,000 objects, will this script fail to show the rest of the files, or does Boto3 handle pagination automatically?

AL 06-02-2025

Michael, that's a crucial point! list_objects_v2 only returns up to 1,000 items per call. In professional Software Development, you should use a Paginator. It handles the NextContinuationToken for you so you don't miss any data. I switched my Cloud Technology scripts to use paginator = s3.get_paginator('list_objects_v2'), which allows me to loop through millions of objects without the script cutting off prematurely.

0
DA
Answered on 08-02-2025

You can also use the high-level s3.Bucket.objects.all() method if you just want a flat list of every single file without worrying about folders.

SA 09-02-2025

I agree with David. If you don't need to distinguish between directories and files for your Software Development task, the Resource API is much more "Pythonic" and easier to read than the Client API.

Share your thoughts

Your email address will not be published. Required fields are marked (*)

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

Book Free Session