How can i download the files inside a folder on google cloud platform using python?

All*_*len 2 python python-3.x google-cloud-platform

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])
Run Code Online (Sandbox Code Playgroud)

How can i adjust my python code to add something like for filename in os.listdir(path): to just copy all the files in a certain folder on there locally

dse*_*sto 5

首先,我认为值得强调的是,Google Cloud Storage 使用平面名称空间,实际上“目录”的概念并不存在,因为 GCS 中没有存储分层文件架构。有关目录如何工作的更多信息可以在文档中找到,因此如果您对此主题感兴趣,那么这是一本很好的读物。

话虽这么说,您可以使用我在下面分享的脚本,以便将 GCS 中“文件夹”中的所有文件下载到本地环境中的同一文件夹中。基本上,您自己的代码中唯一重要的添加部分是调用该bucket.list_blobs()方法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)
Run Code Online (Sandbox Code Playgroud)