fernando
fernando

Reputation: 23

File upload, using Python(Local System) to Google Cloud Storage

I'm literally stuck on some function. I want to write the code to upload file to Google Cloud Storage using Python, but I don't know where should I start.

I'd looked into docs from everywhere, but it shows only at Google Cloud Shell.

If anyone knows about this, enlighten me please!

Have a good one!

Upvotes: 2

Views: 6860

Answers (2)

Franco
Franco

Reputation: 862

Here's a very easy method

from google.cloud import storage
           
def upload_blob(bucket_name, source_file_name, destination_blob_name):
  """Uploads a file to the bucket."""

  storage_client = storage.Client()

  bucket = storage_client.get_bucket(bucket_name)
  blob = bucket.blob(destination_blob_name)
  blob.upload_from_file(source_file_name)



upload_blob('bucketName', 'myText2.txt', "myText")

Just replace arguments of the function to match your file and bucket.

Upvotes: 0

Let's_Create
Let's_Create

Reputation: 3643

You can do it in this way,

from gcloud import storage

client = storage.Client()

bucket = client.get_bucket('<your-bucket-name>')

blob = bucket.blob('my-test-file.txt')

filename = "%s/%s" % (folder, filename)
blob = bucket.blob(filename)

# Uploading string of text
blob.upload_from_string('this is test content!')

# Uploading from a local file using open()
with open('photo.jpg', 'rb') as photo:
    blob.upload_from_file(photo)

# Uploading from local file without open()
blob.upload_from_filename('photo.jpg')

blob.make_public()
url = blob.public_url

For an explanation of each of the above line check out this blog post (example for the above is taken from this blog): https://riptutorial.com/google-cloud-storage/example/28256/upload-files-using-python

Upvotes: 5

Related Questions