[英]Downloading a file from Google Cloud Storage
我在尝试从 Google Cloud Storage 下载 CSV 文件时遇到问题。 出于某种原因,它一直以字节而不是可读文本的形式下载文件。 当我在 Excel 中打开下载的 CSV 时,Excel 在某种程度上足够聪明,可以将其转换为可读文本。 我在这里想念什么? 我检查了 Google 的文档,但找不到任何好的信息来完成它们。 先感谢您!
storage_client = storage.Client()
bucket = storage_client.bucket("bucket_name")
blob = bucket.blob("csv_file.csv")
blob = blob.download_as_string()
blob = blob.decode('utf-8')
blob = io.StringIO(blob) # tranform bytes to string here
print(blob)
这是错误:UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 15-16: invalid continuation byte
您可以使用官方文档中的代码 function blob.download_to_filename ()
。 你为什么使用blob.download_as_string()
?
from google.cloud import storage
def download_blob(bucket_name, source_blob_name, destination_file_name):
"""Downloads a blob from the bucket."""
# bucket_name = "your-bucket-name"
# source_blob_name = "storage-object-name"
# destination_file_name = "local/path/to/file"
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
# Construct a client side representation of a blob.
# Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve
# any content from Google Cloud Storage. As we don't need additional data,
# using `Bucket.blob` is preferred here.
blob = bucket.blob(source_blob_name)
blob.download_to_filename(destination_file_name)
print(
"Blob {} downloaded to {}.".format(
source_blob_name, destination_file_name
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.