How to Upload a File to Google Cloud Storage on Python 3

To upload a file to Google Cloud Storage on Python 3, you’ll need to use the google-cloud-storage library.

Follow these steps to set up and use the library:

Step 1: Install the library

pip install google-cloud-storage

Step 2: Set up authentication

You can establish authentication by creating a service account and downloading the JSON key file from the Google Cloud Console. Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON key file.

Step 3: Upload a file

Use the following code to upload a file to Google Cloud Storage.

from google.cloud import storage


def upload_blob(bucket_name, source_file_name, destination_blob_name):

  # Initialize the client
  storage_client = storage.Client()

  # Get the bucket object
  bucket = storage_client.get_bucket(bucket_name)

  # Create a blob object and upload the file
  blob = bucket.blob(destination_blob_name)
  blob.upload_from_filename(source_file_name)

  print(f"File {source_file_name} uploaded to {destination_blob_name}")


# Usage example
bucket_name = "your-bucket-name"
source_file_name = "path/to/your/local/file"
destination_blob_name = "path/in/bucket/filename"

upload_blob(bucket_name, source_file_name, destination_blob_name)

Replace your-bucket-name, path/to/your/local/file, and path/in/bucket/filename with appropriate values for your use case. This function uploads the specified local file to the Google Cloud Storage bucket.

That’s it.

Leave a Comment