大家好,感谢大家的阅读。我是新来的GCP,但我仍然找不到解决问题的方法。我搜索了很多话题,但没有一个解决方案能帮助我继续前进。
输入信息
我有文件存储在我的桶在云存储。
这些文件可以是任何扩展名,但我只需要选择.zip
s
我想在App-Engine中编写一个python脚本,它将找到并选择这些zip文件,然后将它们解压缩到Cloud Storage
的同一目录中。脚本的下面版本,它不能工作
from google.cloud import storage
from zipfile import ZipFile
def list_blobs(bucket_name):
storage_client = storage.Client()
blobs = storage_client.list_blobs(bucket_name)
for blob in blobs:
try:
with ZipFile(f'{blob.name}', 'r') as zipObj:
zipObj.extractall()
except:
print(f'{blob.name} not supported unzipping')
list_blobs('test_bucket_for_me_05_08_2021')
输出proxy.txt not supported unzipping
test.zip not supported unzipping
我找到了解决方案,下面的代码将解压缩桶
中的zip。from google.cloud import storage
from zipfile import ZipFile
from zipfile import is_zipfile
import io
storage_client = storage.Client()
def unzip_files(bucketname):
bucket = storage_client.get_bucket(bucketname)
blobs = storage_client.list_blobs(bucketname)
for blob in blobs:
file = bucket.blob(blob.name)
try:
zipbytes = io.BytesIO(file.download_as_string())
if is_zipfile(zipbytes):
with ZipFile(zipbytes, 'r') as selected_zip:
for files_in_zip in selected_zip.namelist():
file_in_zip = selected_zip.read(files_in_zip)
blob_new = bucket.blob(files_in_zip)
blob_new.upload_from_string(file_in_zip)
except:
print(f'{blob.name} not supported')
unzip_files("test_bucket_for_me_05_08_2021")
当然,我将修改这段代码,但这个解决方案是有效的
感谢你的时间和努力