Delete a GCP Bucket Using Python

In this tutorial, we will learn how to delete a Google Cloud Storage bucket using Python.

This is a common operation for cleaning up project resources after use.

Python Code to Delete Bucket

We will use the delete() method of the bucket object.

Python

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

def main():

    # Loads environment variables from a .env file
    load_dotenv()

    # Use environment variables from .env file
    credentials_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
    project_name = os.getenv("project_id")

    # Get the 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)

    # Define the bucket name
    bucket_name = "new-bucket-via-python-sdk2"

    # Get a GCP bucket
    bucket = client.get_bucket(bucket_name)

    # Delete the bucket
    bucket.delete(force=True)

    # Print the bucket name
    print(f"Bucket {bucket.name} is deleted successfully")

# Run the main function
if __name__ == "__main__":
    main()    

Key Steps Explained

Note: