使用Python合并GCS存储桶文件夹文件并转存至另一GCS存储桶
解决方案
可以使用Google Cloud官方的google-cloud-storage库实现这个需求,以下是完整的代码示例及关键说明:
步骤1:安装依赖
确保已经安装了GCS SDK:
pip install google-cloud-storage
步骤2:完整代码实现
from google.cloud import storage def merge_gcs_files(source_bucket_name, source_prefix, destination_bucket_name, destination_blob_name): # 初始化GCS客户端 storage_client = storage.Client() # 获取源存储桶 source_bucket = storage_client.bucket(source_bucket_name) # 列出源前缀下的所有文件(排除前缀本身的空"文件夹"对象) blobs = source_bucket.list_blobs(prefix=source_prefix) blobs = [blob for blob in blobs if not blob.name.endswith('/')] # 获取目标存储桶和目标Blob destination_bucket = storage_client.bucket(destination_bucket_name) destination_blob = destination_bucket.blob(destination_blob_name) # 流式合并并写入(避免大文件占用过多内存) with destination_blob.open('w') as dest_file: for blob in blobs: # 读取源文件内容并写入目标文件 with blob.open('r') as source_file: dest_file.write(source_file.read()) # 可选:在文件之间添加换行分隔符,避免内容粘连 dest_file.write('\n') # 示例调用 if __name__ == "__main__": # 源存储桶和文件夹前缀(对应gs://hello/test/) SOURCE_BUCKET = "hello" SOURCE_PREFIX = "test/" # 目标存储桶和合并后的文件路径(对应gs://hello/test1/merged_file.txt) DEST_BUCKET = "hello" DEST_BLOB = "test1/merged_file.txt" merge_gcs_files(SOURCE_BUCKET, SOURCE_PREFIX, DEST_BUCKET, DEST_BLOB)
关键说明
- 前缀处理:GCS没有实际的文件夹结构,
prefix=source_prefix会列出所有以该前缀开头的对象,需要过滤掉以/结尾的空"文件夹"对象。 - 流式读写:使用
blob.open()方法以文件流的方式操作,避免将大文件全部加载到内存中,适合处理大文件场景。 - 权限配置:确保运行代码的环境(本地/云函数等)拥有源存储桶的读取权限和目标存储桶的写入权限。如果是本地运行,需要设置环境变量
GOOGLE_APPLICATION_CREDENTIALS指向服务账号密钥文件。 - 分隔符可选:如果需要在合并的文件内容之间添加分隔符(比如换行),可以取消代码中
dest_file.write('\n')的注释。
内容的提问来源于stack exchange,提问作者sam
相关产品推荐
相关产品推荐

