Download File from GCP Bucket using Python

In this tutorial, we will learn how to download an object (blob) from a Google Cloud Storage bucket to your local machine using Python.

This is essential when you need to process files stored in the cloud.

Python Code to Download File

We will use the download_to_filename() 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 and file details
    bucket_name = "new-bucket-via-python-sdk"

    # Create a bucket object
    bucket = client.bucket(bucket_name)

    # Get the blob object
    blob = bucket.blob("Dummy.pdf")

    # Download the blob to a local file
    # Check if the blob exists
    if blob.exists():
        blob.download_to_filename("downloaded_blob.pdf")

        # Print confirmation that the blob is downloaded
        print(f"Blob {blob.name} is downloaded successfully.")
    else:
        print(f"The blob {blob.name} does not exist in the bucket {bucket_name}.")

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

Key Steps Explained

Note: Ensure your Python environment has write permission on the local directory where you are downloading the file.