尝试使用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
您将需要使用Bucket对象的list_blobs方法。了解更多关于listing objects in Cloud Storage的信息。
# 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