Python 3.x Python中的Apache Beam-我们可以编写文件页脚吗

Python 3.x Python中的Apache Beam-我们可以编写文件页脚吗,python-3.x,google-cloud-dataflow,apache-beam,Python 3.x,Google Cloud Dataflow,Apache Beam,当我们在ApacheBeam中编写文件时,有一条规定使用以下类的header参数编写文件头 类apache\u beam.io.textio.WriteToText(文件路径前缀,文件名后缀='',追加尾随新行=True,num\u shards=0,shard\u name\u template=无,编码器=ToStringCoder,压缩类型=自动,头=无) 虽然没有现成的页脚,但有人能给出一种技术,通过这种技术可以将页脚添加到写入的文件中吗 预期产量为 Header Row 1 Row 2

当我们在ApacheBeam中编写文件时,有一条规定使用以下类的header参数编写文件头

类apache\u beam.io.textio.WriteToText(文件路径前缀,文件名后缀='',追加尾随新行=True,num\u shards=0,shard\u name\u template=无,编码器=ToStringCoder,压缩类型=自动,头=无)

虽然没有现成的页脚,但有人能给出一种技术,通过这种技术可以将页脚添加到写入的文件中吗

预期产量为

Header
Row 1
Row 2
..
..
Row 1000000
Footer


这似乎是Beam Java SDK当前支持的,但不是Beam Python SDK

作为一个解决方案,您可以考虑将页脚添加到使用随后的<代码> ParDO < /COD>(RealToTeXeX/COD>)的所有文件中,返回所有文件的“<代码> pSc收藏< /代码>”。


为跟踪而创建。

我找到了解决方案。我们需要通过扩展2个类来实现这一点

扩展_TextSink并覆盖
close()
方法

    def close(self, file_handle):
    if self._footer is not None:
        self.write_record(file_handle, self._footer)
    file_handle.close()
扩展
PTransform
类来编写您自己的编写器

class MyWriteToText(PTransform):
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.AUTO, header=None, footer=None):
    self._sink = _TheExtendedSink(
        file_path_prefix, file_name_suffix, append_trailing_newlines,
        num_shards, shard_name_template, coder=coders.ToStringCoder(),
        compression_type=compression_type, header=header, footer=footer)

def expand(self, pcoll):
    return pcoll | Write(self._sink)

你们看过模块了吗?文档中指出,您可能需要调整
open()
和/或
close()
函数来自定义文件处理或写入页眉/页脚。@Peter解决方案有效,下面的答案中说明了实现方法。我们需要覆盖一个接收器并指向自定义写入程序中的接收器。