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

How to create text file in Google Cloud Storage without saving it locally?

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

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)

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

!touch localfile
!echo "contents of my file" > localfile
!cat localfile  # outputs: contents of my file

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

upload_blob('my-project','localfile','gcsfile')

确实上传了:

如何在包含字符串 contents of my file 的 Google 云存储中创建 gcsfile,而不先保存它?


我试过了:

import io

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

upload_blob('adventdalen-003',output,'out')

不起作用,我得到:

TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO

相似但不同的线程:

这些都不在 Python 中。

使用@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")

保存在 Google 云存储中:

里面 from_string.txt: