如何在 Google Cloud Storage 中创建文本文件而不将其保存在本地?

zab*_*bop 2 python google-cloud-storage google-cloud-platform

我知道如何将保存到文本文件的字符串上传到 Google Cloud Storage:使用upload_blob下面的函数(来源):

from google.cloud import storage

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The path to your file to upload
    # source_file_name = "local/path/to/file"
    # The ID of your GCS object
    # destination_blob_name = "storage-object-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name)
Run Code Online (Sandbox Code Playgroud)

我可以创建一个存储在本地磁盘上的文件:

!touch localfile
!echo "contents of my file" > localfile
!cat localfile  # outputs: contents of my file
Run Code Online (Sandbox Code Playgroud)

将此文件上传到 Google 云存储:

upload_blob('my-project','localfile','gcsfile')
Run Code Online (Sandbox Code Playgroud)

确实已上传:

在此输入图像描述

如何gcsfile在 Google Cloud Storage 中创建包含 string 的内容contents of my file,而不先保存它?


我试过:

import io

output = io.BytesIO()
output.write(b'First line.\n')

upload_blob('adventdalen-003',output,'out')
Run Code Online (Sandbox Code Playgroud)

不起作用,我得到:

TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO
Run Code Online (Sandbox Code Playgroud)

相似但不同的线程:

这些都不是 Python 中的。

小智 7

使用@johnhanley的建议,这是实现 blob.upload_from_string() 的代码:

from google.cloud import storage

def write_to_blob(bucket_name,file_name):
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(file_name)
    blob.upload_from_string("written in python")

write_to_blob(bucket_name="test-bucket",file_name="from_string.txt")
Run Code Online (Sandbox Code Playgroud)

保存在 Google 云存储中:

在此输入图像描述

里面from_string.txt

在此输入图像描述