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

标签 python python-3.x google-cloud-storage gcloud-python

我已经成功实现了将文件上传到 Google Cloud Storage 存储桶的 python 函数,但我想将它添加到存储桶中的子目录(文件夹),当我尝试将它添加到存储桶名称时,代码失败找到文件夹。

谢谢!

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

最佳答案

您在错误的位置添加了“文件夹”。请注意,Google Cloud Storage 没有真正的文件夹或目录(请参阅 Object name considerations )。

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

  • bucket = 桶/文件夹名
  • 对象 = 对象名

你会想要:

  • 桶 = 桶
  • object = 文件夹名/对象名

对于您的代码,我认为这应该可行:

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

关于python - 使用 Python 将文件上传到 Google Cloud Storage Bucket 子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47141291/

相关文章:

python - Blob.generate_signed_url() 未能出现 AttributeError

node.js - Google Cloud Storage - 权限不足

python - 如何在不评估的情况下拆分 Django 查询集?

Python 3 - 我是否正确使用了索引?

python-3.x - 使用 librosa.resample 后为 "wave.Error: unknown format: 3"。 librosa的输出有什么问题吗?

python - 如何使用 python 检查日期是否为空?

python - 使用 Python 对 Google Storage 进行身份验证

python - 在 scikit-learn ML 算法中使用 float64 数据类型是否正确?

python - 一个列表包含另一个具有重复的列表

python - 使用正则表达式在python中的两个字符串之间提取字符串