【问题标题】:How can i download the files inside a folder on google cloud platform using python?如何使用 python 下载谷歌云平台文件夹中的文件?
【发布时间】:2018-08-03 08:05:15
【问题描述】:
from google.cloud import storage
client = storage.Client()
bucket = client.get_bucket([bucket_name])
blob = bucket.get_blob([path to the .txt file])
blob.download_to_filename([local path to the downloaded .txt file])

如何调整我的 python 代码以添加类似for filename in os.listdir(path): 的内容,以便将某个文件夹中的所有文件复制到本地

【问题讨论】:

    标签: python python-3.x google-cloud-platform


    【解决方案1】:

    首先,我认为有趣的是要强调 Google Cloud Storage 使用平面命名空间,实际上“目录”的概念并不存在,因为 GCS 中没有存储分层文件架构。有关how directories work 的更多信息可以在文档中找到,因此如果您对此主题感兴趣,不妨阅读一下。

    话虽如此,您可以使用我在下面分享的脚本,以便将 GCS 中“文件夹”中的所有文件下载到本地环境中的同一文件夹中。基本上,您自己的代码中唯一重要的附加部分是正在调用 bucket.list_blobs() method,其中 prefix 字段指向文件夹名称,以便查找仅与名称中的文件夹模式匹配的 blob .然后,遍历它们,丢弃目录 blob 本身(在 GCS 中,它只是一个名称以 "/" 结尾的 blob),然后下载文件。

    from google.cloud import storage
    import os
    
    # Instantiate a CGS client
    client=storage.Client()
    bucket_name= "<YOUR_BUCKET_NAME>"
    
    # The "folder" where the files you want to download are
    folder="<YOUR_FOLDER_NAME>/"
    
    # Create this folder locally
    if not os.path.exists(folder):
        os.makedirs(folder)
    
    # Retrieve all blobs with a prefix matching the folder
    bucket=client.get_bucket(bucket_name)
    blobs=list(bucket.list_blobs(prefix=folder))
    for blob in blobs:
        if(not blob.name.endswith("/")):
            blob.download_to_filename(blob.name)
    

    【讨论】:

      猜你喜欢
      • 2020-12-11
      • 1970-01-01
      • 2018-07-18
      • 2017-07-22
      • 2018-04-06
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      相关资源
      最近更新 更多