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):
只需将某个文件夹中的所有文件复制到本地
首先,我认为值得强调的是,Google Cloud Storage 使用平面名称空间,实际上“目录”的概念并不存在,因为 GCS 中没有存储分层文件架构。有关更多信息目录如何工作可以在文档中找到,因此如果您对此主题感兴趣,那么值得一读。
话虽这么说,您可以使用我在下面分享的脚本,以便将 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)