如何为apache beam数据流的输出csv添加标题?

2024-09-27 20:19:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这些特性是否反映在pythonskd上?在


Tags: 文件csv函数httpsiocomcloudgoogle
3条回答

目前还没有实现。但是,您可以自己实现/扩展它(请参见attached notebook以获取使用我的apache_beam版本进行的示例+测试)。在

这是基于超类FileSink的一个note in the docstring,提到您应该覆盖open函数:

适用于我的apache_beam('0.3.0)版本的新类-孵化器.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

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

^{2}$

有关完整的概述,请参见the notebook。在

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

来自文档:

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)

因此您可以使用以下代码:

^{2}$

如果您需要详细信息或检查它是如何实现的,这里提供了完整的文档:https://beam.apache.org/documentation/sdks/pydoc/2.0.0/_modules/apache_beam/io/textio.html#WriteToText

pythonsdk中还没有这个特性

相关问题 更多 >

    热门问题