Cloud Storage client library

Create a storage bucket

from google.cloud import storage
client = storage.Client()
print("Client created using default project: {}".format(client.project))
# client = storage.Client(project='your-project-id')
# Replace the string below with a unique name for the new bucket
bucket_name = "your-new-bucket"

# Creates the new bucket
bucket = client.create_bucket(bucket_name)

print("Bucket {} created.".format(bucket.name))

List buckets in a project

buckets = client.list_buckets()

print("Buckets in {}:".format(client.project))
for item in buckets:
print("\t" + item.name)

Get bucket metadata

bucket = client.get_bucket(bucket_name)

print("Bucket name: {}".format(bucket.name))
print("Bucket location: {}".format(bucket.location))
print("Bucket storage class: {}".format(bucket.storage_class))

Upload a local file to a bucket

blob_name = "us-states.txt"
blob = bucket.blob(blob_name)

source_file_name = "resources/us-states.txt"
blob.upload_from_filename(source_file_name)

print("File uploaded to {}.".format(bucket.name))

List blobs in a bucket

blobs = bucket.list_blobs()

print("Blobs in {}:".format(bucket.name))
for item in blobs:
print("\t" + item.name)

Get a blob and display metadata

blob = bucket.get_blob(blob_name)

print("Name: {}".format(blob.id))
print("Size: {} bytes".format(blob.size))
print("Content type: {}".format(blob.content_type))
print("Public URL: {}".format(blob.public_url))

Download a blob to a local directory

output_file_name = "resources/downloaded-us-states.txt"
blob.download_to_filename(output_file_name)

print("Downloaded blob {} to {}.".format(blob.name, output_file_name))

Cleaning up

Delete a blob

blob = client.get_bucket(bucket_name).get_blob(blob_name)
blob.delete()

print("Blob {} deleted.".format(blob.name))

Delete a bucket

bucket = client.get_bucket(bucket_name)
bucket.delete()

print("Bucket {} deleted.".format(bucket.name))

Next Steps

--

--

--

Machine Learning Scientist

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Android fundamentals 04.4: User navigation

Networking Basics

What does data engineering entail?

My Life Before Flatiron School

I’m Beginning to Wonder if It Was Worth It

Monitoring apps on kubernetes from Prometheus running outside kubernetes cluster

Hello Halagame

🔰How to Write an Ansible Play-Book To: 🔹 Configure Docker 🔹Setting up a Webserver

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mohamed Niang

Mohamed Niang

Machine Learning Scientist

More from Medium

Temperature sensing for Jupiter Garage

On-Premise vs. Cloud: Key Differences, Pros, and Cons

ElastAlert 2 for OpenShift 4.9

Finding nearest neighbour with Cloud Firestore.