python-3.x - 在 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
解决方案
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
推荐阅读
- java - 使用 OpenJDK 启动 Docker 容器时出现“Powershell”错误:Windowsservercore
- r - 如何在面板数据集中创建多个国家/地区的 5 年平均值?
- c# - 如何在 Azure DevOps Services 中使用 TfvcHttpClient 创建 TfvcLabel?
- javascript - (恶意)用户可以在运行时编辑我的 JavaScript 代码吗?
- javascript - 如何在 codemirror 中识别 javascript?
- c# - 如何在没有任何警报且不使用任何路径或文件名的情况下以只读方式打开 excel 文件?
- jboss - JDWP 传输 dt_socket 初始化失败,TRANSPORT_INIT(510)
- c++ - 使用openmp优化内部循环依赖于外部循环的并行嵌套循环
- angular - Angular 中 FormArray 的自定义验证器运行次数过多
- python - AttributeError:“CombinedExpression”对象没有属性“default_alias”