[英]Downloading a file from google cloud storage inside a folder
我有一个python脚本,它获取已上传到谷歌云存储桶的文件列表,并尝试以字符串形式检索数据。
代码很简单:
file = open(base_dir + "/" + path, 'wb')
data = Blob(path, bucket).download_as_string()
file.write(data)
我的问题是我上传的数据存储在存储桶中的文件夹中,因此路径类似于:
folder/innerfolder/file.jpg
当谷歌图书馆试图下载该文件时,它会以GET请求的形式获取该文件,从而将上述路径转换为:
https://www.googleapis.com/storage/v1/b/bucket/o/folder%2Finnerfolder%2Ffile.jpg
有没有办法阻止这种情况发生/通过这种方式下载文件? 干杯。
是的 - 您可以使用python 存储客户端库执行此操作。
只需使用pip install --upgrade google-cloud-storage
安装它,然后使用以下代码:
from google.cloud import storage
# Initialise a client
storage_client = storage.Client("[Your project name here]")
# Create a bucket object for our bucket
bucket = storage_client.get_bucket(bucket_name)
# Create a blob object from the filepath
blob = bucket.blob("folder_one/foldertwo/filename.extension")
# Download the file to a destination
blob.download_to_filename(destination_file_name)
您也可以使用.download_as_string()
但是当您将其写入文件时,无论如何直接下载到文件可能会更容易。
要注意的唯一有点尴尬的事情是文件路径是来自桶名称之后的路径,因此不会与Web界面上的路径完全对齐。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.