Google Cloud SDK Python客户端:如何列出云存储桶中的文件?

问题描述 投票:0回答:2

尝试使用Python来获取并遍历我拥有的云存储桶中的所有文件。我正在使用官方图书馆,google-cloud-storage

使用gsutil,我可以运行像gsutil ls gs://my-composer-bucket/dags/composer_utils/这样的命令。 google-cloud-storage图书馆是否提供与gsutil ls等效的方法?我想使用Python客户端而不是shell来gsutil(不想在Docker镜像中安装和验证GCloud SDK)。

我尝试了一些不同的东西让我对blob的工作方式感到困惑:

>>> dag_folder_blob = cloud_composer_bucket.blob(bucket, 'dags/')
>>> dag_folder_blob.exists()
True
>>> util_folder_blob = cloud_composer_bucket.blob(bucket, 'dags/composer_utils/')  # directory exists
>>> util_folder_blob.exists()
False
>>> util_file_blob = cloud_composer-bucket.blob(bucket, 'dags/composer_utils/__init__.py')
>>> util_file_blob.exists()
True
python google-cloud-platform google-cloud-storage
2个回答
3
投票

您将需要使用Bucket对象的list_blobs方法。了解更多关于listing objects in Cloud Storage的信息。


1
投票
# replicating command: gsutil ls gs://<bucketName>/<prefix>

from google.cloud import storage
bucket = storage.Client(<proj>).bucket(<bucketName>)
for key in bucket.list_blobs(prefix=<prefix>):
    print key
© www.soinside.com 2019 - 2024. All rights reserved.