【发布时间】:2017-09-26 17:01:05
【问题描述】:
我找不到使用 python 将本地计算机中的数据集写入谷歌云存储的方法。我进行了很多研究,但没有找到任何关于此的线索。需要帮助,谢谢
【问题讨论】:
-
你找到方法了吗?似乎人们倾向于将上传与实际写入混淆
标签: python-3.x google-cloud-platform google-cloud-storage
我找不到使用 python 将本地计算机中的数据集写入谷歌云存储的方法。我进行了很多研究,但没有找到任何关于此的线索。需要帮助,谢谢
【问题讨论】:
标签: python-3.x google-cloud-platform google-cloud-storage
快速示例,使用google-cloud Python 库:
from google.cloud import storage
def upload_blob(bucket_name, source_file_name, destination_blob_name):
"""Uploads a file to the bucket."""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print('File {} uploaded to {}.'.format(
source_file_name,
destination_blob_name))
更多示例在此 GitHub 存储库中:https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/storage/cloud-client
【讨论】:
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
service = discovery.build('storage', 'v1', credentials=credentials)
filename = 'file.csv'
bucket = 'Your bucket name here'
body = {'name': 'file.csv'}
req = service.objects().insert(bucket=bucket, body=body, media_body=filename)
resp = req.execute()
【讨论】:
from google.cloud import storage
def WriteToCloud ( buffer ):
client = storage.Client()
bucket = client.get_bucket( 'bucket123456789' )
blob = bucket.blob( 'PIM.txt' )
blob.upload_from_file( buffer )
虽然 Brandon 的回答确实将文件发送到 Google 云,但它通过上传文件而不是写入文件来做到这一点。这意味着在您将文件上传到云之前,该文件需要存在于您的磁盘上。我提出的解决方案使用“内存中”有效负载(“缓冲区”参数),然后将其写入云。要编写内容,您需要使用“upload_from_file”而不是“upload_from_filename”,其他一切都相同。
【讨论】:
在较早的答案中,我仍然怀念最简单的方法,使用 open() 方法。
您可以按如下方式使用 blob.open():
from google.cloud import storage
def write_file():
client = storage.Client()
bucket = client.get_bucket('bucket-name')
blob = bucket.blob('path/to/new-blob-name.txt')
## Use bucket.get_blob('path/to/existing-blob-name.txt') to write to existing blobs
with blob.open(mode='w') as f:
for line in object:
f.write(line)
您可以在此处找到更多示例和 sn-ps: https://github.com/googleapis/python-storage/tree/main/samples/snippets
【讨论】:
我一直在寻找相同的答案,终于找到了。当我们想要从字符串到 GCS 存储桶的解决方案时,只需在最后一行更改:
from google.cloud import storage
def WriteToCloud ( your_string_name ):
client = storage.Client()
bucket = client.get_bucket( 'bucket123456789' )
blob = bucket.blob( 'PIM.txt' )
blob.upload_from_string( your_string_name )
【讨论】: