使用 Python 将目录中的所有文件上传到 Google Cloud 存储桶

问题描述

我已经自动化了一个过程,将 XML 文件从多个设备提取到我的盒子中,位于 c:\scripts\googlebucket\uploads 的位置

我的任务是将此目录中的所有文件上传到 Google Cloud Bucket。还提供了凭据 JSON 文件以访问 Google Cloud 位置。

我一直在尝试成功上传单个文件,但我正在努力弄清楚如何转储特定目录中的所有文件(c:\scripts\googlebucket 中的所有文件\上传到谷歌云存储桶)。

这是我一直在启动以推送单一文件的脚本:

from google.cloud import storage
client = storage.Client.from_service_account_json(json_credentials_path='Service_Account.json')
bucket = client.get_bucket('us-client-uploads')
blob = bucket.blob(f"Closed_24.02.2021.08.24.xml")
blob.upload_from_filename(f"Closed_24.02.2021.08.24.xml")

有人碰巧有什么建议吗?非常感谢。

解决方法

据我所知,Google Storage Python 库没有提供任何帮助,因此您需要在 Python 中遍历目录中的文件并使用您已经在使用的 upload_from_filename 方法,类似这样:

from os import listdir
from os.path import isfile,join
folder = '<your folder>'
files = [f for f in listdir(folder) if isfile(join(folder,f))]
for file in files:
    local_file = folder + file
    blob = bucket.blob(file)
    blob.upload_from_filename(local_file)