如何使用googlecloudpythonapi将目录复制到google云存储?

2024-04-24 16:36:21 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的函数很适合将单个文件复制到google云存储。在

#!/usr/bin/python3.5
import googleapiclient.discovery

from google.cloud import storage

def upload_blob(bucket_name, source_file_name, destination_blob_name, project):
  storage_client = storage.Client(project=project)
  bucket = storage_client.get_bucket(bucket_name)
  blob = bucket.blob(destination_blob_name)

blob.upload_from_filename(source_file_name)

print('File {} uploaded to {}.'.format(
    source_file_name,
    destination_blob_name))

现在我没有给出文件名,而是尝试输入一个目录名,upload_blob('mybucket','/data/inputdata/', 'myapp/inputdata/','myapp') 但是我得到了一个错误:

AttributeError: 'str' object has no attribute 'read'

在调用函数blob.upload_from_file()复制目录时,是否需要提供任何其他参数?在


Tags: namefromimportprojectclientsourcebucketgoogle
2条回答

一次上载多个文件不是API的内置功能。您可以在一个循环中复制多个文件,也可以使用命令行实用程序,它可以复制整个目录。在

下面是一些代码,您可以使用这些代码来完成此操作:

import os
import glob

def copy_local_directory_to_gcs(local_path, bucket, gcs_path):
    """Recursively copy a directory of files to GCS.

    local_path should be a directory and not have a trailing slash.
    """
    assert os.path.isdir(local_path)
    for local_file in glob.glob(local_path + '/**'):
        if not os.path.isfile(local_file):
            continue
        remote_path = os.path.join(gcs_path, local_file[1 + len(local_path) :])
        blob = bucket.blob(remote_path)
        blob.upload_from_filename(local_file)

这样使用:

^{pr2}$

相关问题 更多 >