无法使用python从google云存储下载对象

2024-04-19 02:26:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用python而不是googlecloudsdk从google云存储下载对象。这是我的代码:

#Imports the Google Cloud client library
from google.cloud import storage
from google.cloud.storage import Blob

# Downloads a blob from the bucket
def download_blob(bucket_name, source_blob_name, destination_file_name):
    storage_client = storage.Client()
    bucket = storage_client.get_bucket('sora_mue')
    blob = bucket.blob('01N3P*.ubx')
    blob.download_to_filename('C:\\Users\\USER\\Desktop\\Cloud')

    print ('Blob {} downloaded to {}.'.format(source_blob_name,
                                             destination_file_name))

问题是在我运行它之后,没有发生任何事情,也没有结果。我做错什么了吗?非常感谢你的帮助!在


Tags: thenamefromimportclientcloudsourcebucket
1条回答
网友
1楼 · 发布于 2024-04-19 02:26:06

TL;DR—您已经在python中定义了一个函数,但尚未调用它。调用函数实际上应该执行代码,从Google云存储桶中提取blob并将其复制到本地目标目录。在

另外,您在函数中接受了参数,但没有使用它们,而是对blob name、GCS bucket name、destination path使用硬编码值。虽然这会起作用,但它首先会破坏定义函数的目的。在

工作实例

下面是一个工作示例,它使用函数中的参数来调用GCS。在

from google.cloud import storage

# Define a function to download the blob from GCS to local destination
def download_blob(bucket_name, source_blob_name, destination_file_name):
  storage_client = storage.Client()
  bucket = storage_client.get_bucket(bucket_name)
  blob = bucket.blob(source_blob_name)
  blob.download_to_filename(destination_file_name)
  print ('Blob {} downloaded to {}.'.format(source_blob_name, destination_file_name))

# Call the function to download blob '01N3P*.ubx' from GCS bucket
# 'sora_mue' to local destination path 'C:\\Users\\USER\\Desktop\\Cloud'
download_blob('sora_mue', '01N3P*.ubx', 'C:\\Users\\USER\\Desktop\\Cloud')
# Will print
# Blob 01N3P*.ubx downloaded to C:\Users\USER\Desktop\Cloud.

相关问题 更多 >