问题描述
以下代码片段来自 Google 教程,它只是打印给定存储桶中 GCP 上文件的名称:
from google.cloud import storage
def list_blobs(bucket_name):
"""Lists all the blobs in the bucket."""
# bucket_name = "your-bucket-name"
storage_client = storage.Client()
# Note: Client.list_blobs requires at least package version 1.17.0.
blobs = storage_client.list_blobs(bucket_name)
for blob in blobs:
print(blob.name)
list_blobs('sn_project_data')
从命令行我可以运行:
$ python path/file.py
在我的终端中,上述存储桶中的文件被打印出来。太好了,它有效! 然而,这并不是我的目标。我想打开一个文件并对其采取行动。例如:
df = pd.read_excel(filename)
print(df.iloc[0])
但是,当我将路径传递给上述内容时,返回的错误显示为“文件路径无效”。所以我确定有某种特定于 GCP 的函数调用来实际访问这些文件......
我应该运行什么命令?
编辑:此视频 https://www.youtube.com/watch?v=ED5vHa3fE1Q 展示了打开文件的技巧,需要在此过程中使用 StringIO。但是它不支持excel文件,所以不是一个有效的解决方案。
解决方法
read_excel() 目前不支持谷歌云存储文件路径,但可以读取字节的数据。
pandas.read_excel(io,sheet_name=0,header=0,names=None,index_col=None,usecols=None,squeeze=False,dtype=None,engine=None, 转换器=无,true_values=无,false_values=无,skiprows=无, nrows=None,na_values=None,keep_default_na=True,na_filter=True,详细=假,解析日期=假,日期解析器=无,千=无, 评论=无,skipfooter=0,convert_float=True,mangle_dupe_cols=True, storage_options=None)
参数:io:str、bytes、ExcelFile、xlrd.Book、path 对象,或 类文件对象
您可以做的是使用 blob 对象并使用 download_as_bytes() 将对象转换为字节。
将此 blob 的内容下载为字节对象。
在这个例子中,我只使用了一个 random sample xlsx 文件并阅读了第一张纸:
from google.cloud import storage
import pandas as pd
bucket_name = "your-bucket-name"
blob_name = "SampleData.xlsx"
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)
data_bytes = blob.download_as_bytes()
df = pd.read_excel(data_bytes)
print(df)