![](/img/trans.png)
[英]How would I loop through all the file names in a subdirectory on Google Cloud Storage with python?
[英]Cycle through subdirectory in google cloud storage
我在谷歌雲中有一個存儲桶。 我有幾個目錄,我在其中創建了文件。
我知道如果我想循環瀏覽其中一個目錄中的所有文件,我可以使用以下命令:
for file in list(source_bucket.list_blobs(prefix='subdir/subdir2')):
file_path=f"gs://{file.bucket.name}/{file.name}"
print(file_path)
但是,結果包括我試圖循環通過的實際路徑,
gs://bucket-name/subdir/subdir2 <----- this item
gs://bucket-name/subdir/subdir2/file1
gs://bucket-name/subdir/subdir2/file2
....
有沒有辦法在目錄不出現的情況下循環瀏覽目錄,使其看起來像這樣。
gs://bucket-name/subdir/subdir2/file1
gs://bucket-name/subdir/subdir2/file2
....
我設法做到了:
subdir = 'subdir1/subdir2/'
for file in list(source_bucket.list_blobs(prefix=subdir)):
file_path = f"gs://{file.bucket.name}/{file.name}"
if file.name == subdir:
continue
else:
print(file_path)
但是有沒有使用谷歌存儲 api 的更清潔的方法呢? 我試圖查找文檔,但沒有看到類似的內容。
Cloud Storage 實際上沒有目錄,它是一個扁平結構。 控制台只是通過使用類似於文件系統的模式命名對象來使其看起來像一個層次結構。 因此,當您請求特定“文件夾”中的所有對象時,您只是請求以相同前綴開頭的所有對象,因此您將獲得整個“子層次結構”。
您可以查看https://cloud.google.com/storage/docs/naming-objects了解更多信息。 這是相關位:
Object 名稱駐留在存儲桶內的平面命名空間中。 這意味着:
Different buckets can have objects with the same name. Objects do not reside within subdirectories in a bucket.
例如,您可以將 object 命名為 /europe/france/paris.jpg 以使其看起來 paris.jpg 位於 /europe/france 子目錄中,但對於 Cloud Storage,object 僅存在於存儲桶中並且名稱為 /歐洲/法國/paris.jpg。 因此,雖然在 Cloud Storage 中使用斜線分隔符的深度嵌套的類目錄結構是可能的,但在列出深度嵌套的子目錄時,它們不具備原生文件系統的性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.