【问题标题】:Walking a directory tree inside a Google Cloud Platform bucket in Python在 Python 中遍历 Google Cloud Platform 存储桶内的目录树
【发布时间】:2020-11-24 18:02:12
【问题描述】:

对于本地机器上的目录,os.walk() 方法通常用于在 Python 中遍历目录树。

Google 有一个 Python 模块 (google.cloud.storage),用于在本地运行的 Python 脚本中上传到 GCP 存储桶并从中下载。

我需要一种方法来遍历 GCP 存储桶中的目录树。我浏览了google.cloud Python 模块中的类,但找不到任何东西。有没有办法在 GCP 存储桶内的目录上执行类似于 os.walk() 的操作?

【问题讨论】:

  • 似乎没有开箱即用的 Google 存储 API 的任何 os.walk() 方法。可能您可以尝试列出从googlecloudplatform.github.io/google-cloud-python/latest/… 找到的存储桶下的文件问题是,在后台,Google 存储不会以我们在 linux 中称为“目录”的方式查看目录。它的所有文件。例如:对象 gs://your-bucket/abc/def.txt 只是一个名称中恰好有“/”字符的对象。没有“abc”目录;只是一个具有给定名称的对象

标签: python google-cloud-platform google-cloud-storage


【解决方案1】:

GCS 库中不存在此类函数。但是,GCS 可以按前缀列出对象,这通常足够等效:

from google.cloud import storage

bucket = storage.Client().get_bucket(bucket_name)
for blob in bucket.list_blobs(prefix="dir1/"):
  print(blob.name)

【讨论】:

    【解决方案2】:
    import os
    from google.cloud import storage
    
    client = storage.Client()
    bucket = client.get_bucket('bucket_name')
    
    for blob in bucket.list_blobs(prefix=''):
       # Download the file
        with open(blob.name, 'wb') as file_obj:
            client.download_blob_to_file(blob, file_obj)
    
       # You logic on the file
       # logic goes here
    
       # Remove the local file
       os.remove(blob.name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      • 2011-08-29
      相关资源
      最近更新 更多