I know how to upload a string saved to a text file to Google Cloud Storage: using the upload_blob
function below (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)
I can create a file stored on local disk:
!touch localfile
!echo "contents of my file" > localfile
!cat localfile # outputs: contents of my file
Upload this file to Google Cloud Storage:
upload_blob('my-project','localfile','gcsfile')
It is indeed uploaded:
How can I create gcsfile
in Google Cloud Storage containing the string contents of my file
, without saving it first?
I tried:
import io
output = io.BytesIO()
output.write(b'First line.\n')
upload_blob('adventdalen-003',output,'out')
Doesn't work, I get:
TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO
Similar but different threads:
Neither of these are in Python.