如何为apache beam dataflow的输出csv添加标头?

时间:2016-09-21 19:15:08

标签: python google-cloud-dataflow apache-beam

我注意到在java sdk中,有一个函数允许你编写csv文件的头文件。 https://cloud.google.com/dataflow/java-sdk/JavaDoc/com/google/cloud/dataflow/sdk/io/TextIO.Write.html#withHeader-java.lang.String-

这个功能是否在python skd上镜像了?

4 个答案:

答案 0 :(得分:3)

您现在可以使用文本接收器写入文本并指定标题。

来自文档:

class apache_beam.io.textio.WriteToText(file_path_prefix, file_name_suffix='', append_trailing_newlines=True, num_shards=0, shard_name_template=None, coder=ToStringCoder, compression_type='auto', header=None)

所以你可以使用以下代码:

beam.io.WriteToText(bucket_name, file_name_suffix='.csv', header='colname1, colname2')

如果您需要详细信息或查看其实施方式,请在此处获取完整的文档:https://beam.apache.org/documentation/sdks/pydoc/2.0.0/_modules/apache_beam/io/textio.html#WriteToText

答案 1 :(得分:1)

目前尚未实施。但是您可以自己实现/扩展它(请参阅attached notebook以获取我的apache_beam版本的示例+测试)。

这是基于超级FileSink的{​​{3}},提到您应该覆盖open函数:

适用于我的apache_beam版本('0.3.0-incubating.dev')的新类:

import apache_beam as beam
from apache_beam.io import TextFileSink
from apache_beam.io.fileio import ChannelFactory,CompressionTypes
from apache_beam import coders


class TextFileSinkWithHeader(TextFileSink):
    def __init__(self,
               file_path_prefix,
               file_name_suffix='',
               append_trailing_newlines=True,
               num_shards=0,
               shard_name_template=None,
               coder=coders.ToStringCoder(),
               compression_type=CompressionTypes.NO_COMPRESSION,
               header=None):
        super(TextFileSinkWithHeader, self).__init__(
            file_path_prefix,
            file_name_suffix=file_name_suffix,
            num_shards=num_shards,
            shard_name_template=shard_name_template,
            coder=coder,

            compression_type=compression_type,
            append_trailing_newlines=append_trailing_newlines)
        self.header = header

    def open(self, temp_path):
        channel_factory = ChannelFactory.open(
            temp_path,
            'wb',
            mime_type=self.mime_type)
        channel_factory.write(self.header+"\n")
        return channel_factory

您可以随后按如下方式使用它:

beam.io.Write(TextFileSinkWithHeader('./names_w_headers',header="names"))

有关完整概述,请参阅note in the docstring

答案 2 :(得分:0)

Python SDK中尚不存在此功能

答案 3 :(得分:0)

对于 Python SDK:

_mockWatermarkOffsets.Object.Low = 10