使用python在google云存储桶中创建文件夹

时间:2018-05-21 19:36:28

标签: python google-cloud-platform google-cloud-storage google-cloud-python

我正在尝试使用python客户端库在Google云端存储中创建一个包含2个空文件夹的新存储桶。

我提到了GCShttps://google-cloud-python.readthedocs.io/en/latest/storage/client.html)的python客户端库API,我找到了create_bucket()方法,但我还想创建2个文件夹 - 'processed'和'在其中未经处理,但无法找到创建文件夹的方法。任何帮助将不胜感激。

由于

2 个答案:

答案 0 :(得分:1)

GCS有一个扁平的命名空间,即'文件夹的概念。不是内置于服务中,而是由各种客户端实现的抽象。例如,Cloud Storage Web UI(console.cloud.google.com/storage/browser)和gsutil都使用以" /"结尾的对象名称实现文件夹抽象。 因此,您可以通过创建诸如your-bucket / abc / def /之类的对象来创建文件夹 但这只是知道/支持命名约定的客户的文件夹。

答案 1 :(得分:0)

def copyFilesInFolder(self, file_name, src_blob_name, destination_blob_name):
    """Copies a blob from one bucket to another with a new name."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"
    # destination_bucket_name = "destination-bucket-name"
    # destination_blob_name = "destination-object-name"

    # storage_client = storage.Client()

    srcBlob = src_blob_name + '/' + file_name
    destBlob = destination_blob_name + '/' + file_name
    source_blob = self.bucket.blob(srcBlob)
    destination_bucket = storage_client.bucket(destBlob)

    blob_copy = self.bucket.copy_blob(
        source_blob, self.bucket, destBlob
    )
    print(blob_copy)
    print(
        "File {} in bucket {} copied to blob {} in bucket {}.".format(
            file_name,
            src_blob_name,
            file_name,
            destination_blob_name,
        )
    )

    return True

在 GCP 中没有直接创建文件夹的概念。所以我们可以在新文件夹中保存一个新文件,这样即使目标文件夹不存在它也会被创建。