![](/img/trans.png)
[英]Return file from Google Cloud Storage through REST API without downloading locally first
[英]How to create text file in Google Cloud Storage without saving it locally?
我知道如何将保存到文本文件的字符串上传到 Google Cloud Storage:使用下面的upload_blob
function( 来源):
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 Cloud Storage:
upload_blob('my-project','localfile','gcsfile')
确实上传了:
如何在不先保存contents of my file
Google Cloud Storage 中创建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")
保存在谷歌云存储中:
在from_string.txt
里面:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.