【问题标题】:Python script for automating GCP storage UPLOAD用于自动化 GCP 存储的 Python 脚本
【发布时间】:2022-01-24 10:57:17
【问题描述】:

我是 GCP 和 GCP 存储的新手。我想将文件从 PC 上的文件系统上传到 GCS 存储桶。 我找到了以下代码并对其进行了更改。

但我有文件位于这样的文件夹中:\F1\Data\Export\PlayOnUsers\2021\12\ 也就是 2021 年 12 个月 - 12 月

所以在\F1\Data\Export\PlayOnUsers\ 之后它正在改变。

我需要输入与 GCS 类似的格式。我需要创建子存储桶2021\12\

这是怎么做到的? 我也没有看到您放置 GCS 凭据的部分

到目前为止我有这个代码:

    from google.cloud import storage
    
    
    def upload_blob(bucket_name, source_file_name, destination_blob_name):
        """Uploads a file to the bucket."""
        # The ID of your GCS bucket
        bucket_name = "MyBucket-scv"
    
        # The path to your file to upload
        source_file_name = "F1/Data/Export"
    
        # The ID of your GCS object
        destination_blob_name = "storage-object-name"
    
        storage_client = storage.Client()
        bucket = storage_client.bucket(bucket_name)
        blob = bucket.blob(destination_blob_name)
    
        blob.upload_from_filename(source_file_name)
    
        print(
            "File {} uploaded to {}.".format(
                source_file_name, destination_blob_name
            )
        )
    
    upload_blob(.., .., ..)

# how do I pass parameters automated when calling the function?

【问题讨论】:

    标签: python google-cloud-platform file-upload automation gcs


    【解决方案1】:

    Finding Credentials Automatically。使用这些“应用程序默认凭据”是一种很好的做法。您需要做的就是拥有一个具有适当角色|权限的服务帐户,如果您在 GCP 之外运行(即不在 Compute Engine 等上),那么您需要创建一个服务帐户密钥并引用它@987654322 @ 你运行你的代码之前。

    Google Cloud Storage (GCS) 并没有文件夹的概念,也没有“子存储桶”的概念。实际上,GCS 存储桶中的所有内容都称为对象对象名称可能包括 /(这是 *nix 等效于 Windows 的 /)并且通常 (!) 用于表示文件夹路径。

    因此,您只需要担心递归地遍历您的 Windows 文件夹(我将把它留给您),然后对于您的代码找到的每个文件,它需要创建一个您的 GCS 存储桶中的对象包括:

    1. 水桶
    2. 文件夹结构使用/ 而不是\
    3. 文件名

    • \F1|Data\Export\PlayOnUsers\2021\12\x 变为 gs://your-bucket/F1/Data/Exporter/PlayOnUsers/2021/12/x
    • \F1|Data\Export\PlayOnUsers\2022\01\x 变为 gs://your-bucket/F1/Data/Exporter/PlayOnUsers/2022/01/x

    【讨论】:

    • 谢谢!我了解对象。经过几次尝试,我得到了正确的代码。 destination_blob_name = "Consumption/" + os.path.split(source_file_name)[-1] 。制作“对象”。根据文件名,我会将它们放到不同的文件夹中。想想现在我不再需要“/2021/12/”了。如果我的 Bucket 中已经有“Consumption/”,它是否会将文件放入已经存在的对象“Consumption”中?
    • 对不起,要清楚。我刚刚发现所有文件都位于一个文件夹中,并且由于文件名而需要放在不同的文件夹中
    • 然后你想解析文件名并注入/来模仿文件夹结构,即2021-12-31.doc变成gs://bucket/.../2021/12/31/doc或类似的。
    猜你喜欢
    • 2022-10-20
    • 1970-01-01
    • 2013-01-16
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2018-08-18
    相关资源
    最近更新 更多