如何使用脚本中的凭据将 .csv 从 gcs 获取到数据帧中?

Lev*_*Lev 2 google-authentication pandas google-cloud-storage

我一直在尝试将 gcs 中的存储桶直接读入 pandas 数据帧,如下所示:

gcs_df = pandas.read_csv("gs://my_bucket/my_file.csv")

这导致:

gcsfs.utils.HttpError: Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.

由于我尚未在本地计算机中设置任何凭据(根据我读到的内容)。

对于脚本的所有其他功能,我通过以下方式使用服务帐户:

sa_creds = service_account.Credentials.from_service_account_file("my_sa_key.json")

我可以以某种方式将此信息传递到 read_csv 中,这样我就不必在本地计算机中使用该帐户吗?

有任何想法吗?

Lev*_*Lev 7

所以pandas库依赖于 gcsfs 库。因此,要执行上述操作,您需要执行以下操作:

import pandas
import gcsfs

fs = gcsfs.GCSFileSystem(project= <project_id>, token=<json path>)
with fs.open("gs://my_bucket/my_file.csv") as f:
    gcs_df = pandas.read_csv(f)
print(gcs_df)
Run Code Online (Sandbox Code Playgroud)

指以 .json 格式保存为密钥的服务帐户凭据。根据gcsfs 文档,它可以是字典或更多。