【问题标题】:Copy GCS file to another directory in same bucket将 GCS 文件复制到同一存储桶中的另一个目录
【发布时间】:2021-11-03 16:12:30
【问题描述】:

我想将 GCS 存储桶中的几个文件复制到同一存储桶中的另一个文件夹,例如:

文件夹结构

Bucket
 -File1.jpg
 -File2.jpg
 -File3.jpg
 -Folder1

我想使用 python 将此存储桶中的 File1 和 File2 复制到 Folder1。

预期的文件夹结构

Bucket
 -File1.jpg
 -File2.jpg
 -File3.jpg
 -Folder1
   -File1.jpg
   -File2.jpg

【问题讨论】:

  • 问题出在哪里?你能显示你到目前为止的任何代码吗?您遇到任何错误?
  • 问题是什么?

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


【解决方案1】:

我刚试过 它正在工作

    from google.cloud import storage
    import google.auth
    from google.oauth2 import service_account 
    
    def copyblob(filename):    
    credentials = service_account.Credentials.from_service_account_file(filename="cred.json",scopes=["https://www.googleapis.com/auth/cloud-platform"]) 
        gcs_client = storage.Client(credentials=credentials)
            
        bucket_name='bucket1'
        blob_name=filename
        destination_bucket_name='bucket1'
        destination_blob_name='Folder1/'+filename
        source_bucket = gcs_client.bucket(bucket_name)
        source_blob = source_bucket.blob(blob_name)
        destination_bucket = gcs_client.bucket(destination_bucket_name)
        print(destination_bucket)
        blob_copy = source_bucket.copy_blob(
               source_blob, destination_bucket, destination_blob_name
            )
        
        print(
            "Blob {} in bucket {} copied to blob {} in bucket {}.".format(
                source_blob.name,
                source_bucket.name,
                blob_copy.name,
                destination_bucket.name,))
        
          
if __name__=='__main__':
    filee='File1.jpg'
    copyblob(filee)

【讨论】:

    猜你喜欢
    • 2017-01-27
    • 2018-05-22
    • 2021-06-13
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 2017-03-17
    • 2018-11-22
    相关资源
    最近更新 更多