首页 > 解决方案 > 在 GCS 中列出对象也会列出目录

问题描述

我正在尝试从我的 Google 存储桶中打印对象(文件)列表,但结果还包含子目录;温度/。我如何省略这个?Google API Doc 并未表明这应该发生。

我的桶:

gs://my_bucket/temp

我的代码:

from google.cloud import storage

storage_client = storage.Client()
bucket = storage_client.get_bucket(my_bucket)
blobs = bucket.list_blobs(prefix="temp/", delimiter='/')

for blob in blobs:
    print(blob.name)

结果:

temp/
temp/2019-02-01_file1.csv
temp/2019-02-01_file2.csv
temp/2019-02-01_file3.csv
temp/2019-02-01_file4.csv

标签: python-3.xgoogle-cloud-storage

解决方案


I think this approach is the one you desire:

If you want to avoid working over the "subfolder" blob, the fastest way to do it is to directly ignore the "subfolder" blob whenever you are iterating over the blobs.

Here's your code with some minor tweaks i have provided. Also, in case you don't want the "temp/" to show when you are listing them i have used the method "replace" similar to Russel H's answer.

from google.cloud import storage

my_prefix = "temp/"
my_bucket = "my_bucket_name"
storage_client = storage.Client()
bucket = storage_client.get_bucket(my_bucket)
blobs = bucket.list_blobs(prefix = my_prefix, delimiter = '/')

for blob in blobs:
    if(blob.name != my_prefix): # ignoring the subfolder itself 
        print(" Displaying " + blob.name.replace(my_prefix, "")) # if you only want to display the name of the blob

推荐阅读