我想使用 Python 读取/写入 Google Cloud Storage 存储桶中的文件。
假设我在 gs://my_project/data
中有一个文件夹。
如何列出上面文件夹中的文件夹和文件?
如何读写文件?
最佳答案
有几种方法可以执行这些操作。最常见的一种是使用原生 Google Cloud Storage API Python .
特别是,使用此 API 的第 0 步是设置 GCP 身份验证,包括设置服务帐户、下载其 json
凭据并设置一个指向它的环境变量:
export GOOGLE_APPLICATION_CREDENTIALS="[PATH-TO-JSON-CREDS]"
1。列出文件和文件夹
在 GCS 中,there is no notion of a "directory"/"folder" .只有桶和 blob/对象。尽管如此,blob 名称中的 /
可用于模拟类似文件夹的层次结构。
列出 gs://my_project/data
中的 blob:
from google.cloud import storage
client = storage.Client()
bucket = client.bucket('my_project')
blobs = list(bucket.list_blobs(prefix='data/'))
2。读写文件
从 gs://my_project/data
中列出的第一个 blob 中读取。
target_blob = blobs[0]
# read as string
read_output = target_blob.download_as_string()
要写入新的 blob,除了写入本地文件并从文件上传外,我没有找到其他方法。
target_blob = bucket.blob('new_blob.txt')
local_tmp_path = 'tmp.txt'
# write string
with open(local_tmp_path, 'w') as f:
f.write('Hello World')
with open(local_tmp_path, 'r') as f:
target_blob.upload_from_file(f)
关于python - 如何读取、写入和列出谷歌存储桶中的文件夹和文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51980471/