List Google Cloud Storage Buckets using Python

In this tutorial, we will learn how to retrieve a list of all Cloud Storage buckets within your Google Cloud project using Python. This is useful for bucket management and resource discovery.

Python Code to List Buckets

We will use the list_buckets() method of the storage.Client class.

Python

# Import required packages
from dotenv import load_dotenv
import os
from google.oauth2 import service_account
from google.cloud import storage

def main():
    # Load environment variables from .env file
    load_dotenv()

    # Read values from environment variables
    credentials_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
    project_name = os.getenv("project_id")

    # Load service account credentials
    credentials = service_account.Credentials.from_service_account_file(
        credentials_path
    )

    # Create the Storage client
    client = storage.Client(credentials=credentials, project=project_name)

    # List all buckets in the project
    buckets = client.list_buckets()

    if not buckets:
        print(f"No buckets found in project {client.project}.")
    else:
        print(f"Buckets in project {client.project}:")
        for bucket in buckets:
            print(f"Bucket Name: {bucket.name}")

if __name__ == "__main__":
    main()    

Key Steps Explained

Note: Listing buckets requires the storage.buckets.list permission in your project.