从文件夹内的Google云存储下载文件 [英] Downloading a file from google cloud storage inside a folder

查看:192
本文介绍了从文件夹内的Google云存储下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本,该脚本获取已上传到Google云存储桶的文件列表,并尝试以字符串形式检索数据.

I've got a python script that gets a list of files that have been uploaded to a google cloud storage bucket, and attempts to retrieve the data as a string.

代码很简单:

file = open(base_dir + "/" + path, 'wb')
data =  Blob(path, bucket).download_as_string()
file.write(data)

我的问题是我上传的数据存储在存储桶中的文件夹内,因此路径应类似于:

My issue is that the data I've uploaded is stored inside folders in the bucket, so the path would be something like:

folder/innerfolder/file.jpg

当Google库尝试下载文件时,它以GET请求的形式获取文件,该文件将上述路径转换为:

When the google library attempts to download the file, it gets it in the form of a GET request, which turns the above path into:

https://www.googleapis.com/storage/v1/b/bucket/o/folder%2Finnerfolder%2Ffile.jpg

有什么办法可以阻止这种情况/通过这种方式下载文件吗?干杯.

Is there any way to stop this happening / download the file though this way? Cheers.

推荐答案

是-您可以使用python

Yes - you can do this with the python storage client library.

只需使用pip install --upgrade google-cloud-storage安装它,然后使用以下代码:

Just install it with pip install --upgrade google-cloud-storage and then use the following code:

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(),但是当您将其写入文件时,直接下载到该文件可能会更容易.

You can also use .download_as_string() but as you're writing it to a file anyway downloading straight to the file may be easier.

唯一需要注意的一点是,文件路径是存储区名称后 之后的路径,因此与Web界面上的路径并不完全一致.

The only slightly awkward thing to be aware of is that the filepath is the path from after the bucket name, so doesn't line up exactly with the path on the web interface.

这篇关于从文件夹内的Google云存储下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆