使用Python将文件上传到Google Cloud Storage Bucket子目录

sea*_*_oc 11 python python-3.x google-cloud-storage gcloud-python

我已成功实现python函数将文件上传到Google Cloud 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 +"/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))
Run Code Online (Sandbox Code Playgroud)

jte*_*ace 21

您在错误的位置添加"文件夹".请注意,Google云端存储没有真正的文件夹或目录(请参阅命名部分的最后一个子弹).

模拟目录实际上只是一个名称中带有前缀的对象.例如,而不是你现在拥有的:

  • bucket = bucket/folderName
  • object = objectname

你会想要:

  • 桶=桶
  • object = folderName/objectname

对于您的代码,我认为这应该工作:

bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob("folderName/" + destination_blob_name)
blob.upload_from_filename(source_file_name)
Run Code Online (Sandbox Code Playgroud)