如何解决从 Google Cloud Storage 下载文件
我在尝试从 Google Cloud Storage 下载 CSV 文件时遇到问题。出于某种原因,它不断将文件下载为字节而不是可读文本。当我在 Excel 中打开下载的 CSV 时,Excel 以某种方式足够智能,可以将其转换为可读文本。我在这里缺少什么? 我检查了谷歌的文档,但找不到任何关于如何完成它们的好信息。提前致谢!
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
解决方法
您可以使用官方文档中的代码,函数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
)
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。