seanie_oc
seanie_oc

Reputation: 341

Upload File to Google Cloud Storage Bucket Sub Directory using Python

I have successfully implemented the python function to upload a file to Google Cloud Storage bucket but I want to add it to a sub-directory (folder) in the bucket and when I try to add it to the bucket name the code fails to find the folder.

Thanks!

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 +"/folderName") #I tried to add my folder here
  blob = bucket.blob(destination_blob_name)

  blob.upload_from_filename(source_file_name)

  print('File {} uploaded to {}.'.format(
    source_file_name,
    destination_blob_name))

Upvotes: 22

Views: 26302

Answers (1)

jterrace
jterrace

Reputation: 67063

You're adding the "folder" in the wrong place. Note that Google Cloud Storage doesn't have real folders or directories (see Object name considerations).

A simulated directory is really just an object with a prefix in its name. For example, rather than what you have right now:

  • bucket = bucket/folderName
  • object = objectname

You'll instead want:

  • bucket = bucket
  • object = folderName/objectname

In the case of your code, I think this should work:

bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob("folderName/" + destination_blob_name)
blob.upload_from_filename(source_file_name)

Upvotes: 51

Related Questions