从文件夹内的Google云存储下载文件

编程入门 行业动态 更新时间:2024-10-09 18:18:06
本文介绍了从文件夹内的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:

www.googleapis/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云存储下载文件

本文发布于:2023-11-24 14:03:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625511.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件夹   文件   Google

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!