簡體   English   中英

如何使用python遍歷Google Cloud Storage子目錄中的所有文件名?

[英]How would I loop through all the file names in a subdirectory on Google Cloud Storage with python?

假設我在Google Cloud Storage上有一些存儲桶/子目錄,該存儲桶的地址為:

gs://test-monkeys-example/training_data/cats

在這個cats子目錄中,我有一堆貓的圖像,所有圖像都是jpg。 我如何在python中循環通過cats子目錄並打印出其中的所有文件名?

就像是:

for x in directory('gs://test-monkeys-example/training_data/cats'):
    print(x)

顯然,目錄('gs:// test-monkeys-example / training_data / cats')不是如何執行此操作,而只是psuedocode-我將如何執行此操作?

Google雲端存儲僅支持列出以特定前綴開頭的對象。 您可以從客戶端庫訪問它,如下所示:

from google.cloud import storage

client = storage.Client()
bucket = client.bucket('mybucket')
for blob in bucket.list_blobs(prefix='training_data/cats'):
  print blob.name

使用存儲模塊:

import google.datalab.storage as storage
cats = [o.key for o in storage.Bucket('test-monkeys-example').objects()
  if o.key.startswith('training_data/cats')]

這為您提供了此類貓的清單。

另外,您可以使用Objects類:

cats = [o.key for o in storage.Objects('test-monkeys-example', '', '')
  if o.key.startswith('training_data/cats')]

如果不需要將列表放在變量中,則可以使用%gcs魔術,它更簡單:

%gcs list -o gs://test-monkeys-example/training_data/cats/*

這將顯示鍵的HTML表。 請注意,這是完整的GCS路徑,以gs://開頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM