Delete a File from a GCP Bucket using Python
In this tutorial, we will learn how to delete a specific object (blob) from a Cloud Storage bucket using Python. This is a common cleanup operation for managing files programmatically.
Python Code to Delete File
We will use the delete() method of the blob 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-sdk"
# Create a bucket object
bucket = client.bucket(bucket_name)
# Define blob name
blob_name = "test_blob.txt"
# Get the blob object
blob = bucket.blob(blob_name)
# Delete the blob safely
if blob.exists():
blob.delete()
print(f"File {blob_name} deleted from bucket {bucket_name}.")
else:
print(f"File {blob_name} does not exist in bucket {bucket_name}.")
# Confirmation message
print(f"Blob {blob_name} operation completed.")
# Run the main function
if __name__ == "__main__":
main() Key Steps Explained
- bucket.blob(name): Prepares an object path (blob) reference within the bucket.
- blob.exists(): Verifies if the file is present before attempting deletion.
- blob.delete(): Sends the deletion command to Cloud Storage.
Note: Deletion is immediate and permanent. There is no recycle bin for Cloud Storage objects unless object versioning is enabled on the bucket.