【问题标题】:How to create a file inside a GCS bucket from a python list?如何从 python 列表中创建 GCS 存储桶内的文件?
【发布时间】:2022-01-19 15:22:33
【问题描述】:

我正在使用 apache Airflow DAG。 在 DAG 中,我使用的是 python 运算符。 在操作员内部,我在 python 列表中获取了一些数据。 现在我想将列表中的数据保存在谷歌云存储桶内的 txt 文件中,我该怎么做?

import subprocess

output = subprocess.getoutput('gsutil ls gs://my-bucket/*/1/')

#print(output)

li = list(output.split("\n"))

我想在 gcs 存储桶上创建一个包含 li 的文本文件。

【问题讨论】:

    标签: python google-cloud-platform airflow


    【解决方案1】:

    最基本的答案就是将li写入文件系统中的一个文件。

    filehandle = open('temp.txt', 'w')
    filehandle.write(li)
    filehandle.close()
    

    然后,上传到谷歌

    output = subprocess.getoutput('gsutil cp temp.txt gs://my-bucket/')
    

    【讨论】:

      【解决方案2】:

      您可以使用GcsHookupload 函数来做到这一点,该函数将本地文件或文件数据作为字符串或字节上传到谷歌云存储。在 Airflow 中,它更喜欢与 Hooks/Operators/Sensors 一起使用,因为一切都应该已经为它们配置好了。

      我没有测试它,但这应该可以工作:

      from airflow.providers.google.cloud.hooks.gcs import GCSHook
      def python_operator_callable():
          ...
          li = list(output.split("\n"))
          li_str = ', '.join(li) #data parameter accepts string or Bytes. Change this line to a format suitable for you
          hook = GcsHook(gcp_conn_id="conn_name")  # conn_name should be defined in Admin -> Connections
          hook.upload(
              bucket_name="you_bucket",
              object_name="temp.txt",
              data=li_str,
              encoding='utf-8')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-07
        • 2017-12-23
        • 1970-01-01
        • 1970-01-01
        • 2022-10-16
        • 2020-09-17
        相关资源
        最近更新 更多