pythonpython-3.xgoogle-cloud-storagegcloud-python

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))

Solution

  • 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:

    You'll instead want:

    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)