![](/img/trans.png)
[英]How to get all files from a Bucket - IBM Cloud Object Storage?
[英]How to zip all files in a Google cloud storage bucket?
我需要 zip 給定雲存儲桶中的所有文件。 我已經嘗試了幾種替代方案,但到目前為止沒有任何效果。
目前,我只能檢索存儲桶中的 blob,但我還需要生成一個 zip 文件,將所有這些文件分組並將其放在存儲桶中。
你能幫我解決這個問題嗎?
這是到目前為止的代碼:
from google.cloud import storage
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="file.json"
def zip_in_bucket(bucketname):
client = storage.Client()
bucket = client.get_bucket(bucketname)
object_generator = bucket.list_blobs()
for files in object_generator:
print(files.name)
返回:
file-1.csv
file-2.csv
file-3.csv
file-4.csv
file-5.csv
解決這個問題有兩種變體,要么你使用谷歌雲 shell。
gsutil cp -r gs://<<bucketname>>
zip <<NameOfZip>>.zip ./<<*_Filepattern*>>
gsutil cp <<NameOfZip>>.zip gs://<<bucketname>>
或者您可以使用 python 代碼執行此操作。 問題是你必須通過你的雲 function 來 stream 文件。
source_bucket_name = <<bucketname>>
storage_client = storage.Client()
source_bucket = storage_client.get_bucket(source_bucket_name)
blobs = list_blobs_with_prefix(source_bucket_name , prefix='20210702/', delimiter='/')
for i in blobs:
print(i)
filterBlobs = list_blobs_with_prefix(source_bucket_name , prefix=i)
with ZipFile('LOG'+i.split("/")[1]+'_'+i.split("/")[0]+'XXXX.zip', 'w') as zip:
for file in filterBlobs:
data = source_bucket.blob(file).download_as_string()
zip.writestr(file.split("/")[-1],data)
zip.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.